

sky_right_advert = false;

/* konfiguracja wtyczki jQuery mColorPicker: */
$.fn.mColorPicker.init.replace = false;
$.fn.mColorPicker.init.enhancedSwatches = false;
$.fn.mColorPicker.init.allowTransparency = true;
$.fn.mColorPicker.init.showLogo = false;
$.fn.mColorPicker.defaults.imageFolder = 'res/img/mcolorpicker/';
$.fn.mColorPicker.defaults.swatches = [
	"#ffffff",
	"#ffff00",
	"#cc0000",
	"#f02000",
	"#fcd000",
	"#00d000",
	"#0090f0",
	"#005000",
	"#3b3b3b",
	"#000000"
];
 /// dummy for IE8.0 analytics error
var pageTracker = new Object;
pageTracker._trackPageview = function(){};
pageTracker._trackEvent = function(){};

/**
 * Funkcja przyklejania do ekranu jakiegos elementu.
 * Podajemy mu diva wzgledem ktorego ma sie ustawic
 *
 * @example $(".sky").alwaysOnScreen('#main_container') – pozycjonuje sie w odniesieniu do tego elementu
 * @example $(".sky").alwaysOnScreen(); – bierze pod uwage aktualna pozycje diva
 */
(function( $ ){
	$.fn.alwaysOnScreen = function($reference_div) {
		var reference = true;

		if (!$reference_div) {
			$reference_div = $(this);
			reference = false;
		}

		var topstart = $($reference_div).offset().top;
		var $movableDiv = this;
		
		$('.sky').css("top", topstart);

		$movableDiv.css("position", "absolute").css("top", topstart);

		$(window).scroll(function() {
			var y = window.pageYOffset;
			var top = $($reference_div).offset().top;

			if(!reference){
				top = topstart;
			}

			if (top-y < 40) {
				if ("absolute" == $movableDiv.css("position")) {
					$movableDiv.css("position", "fixed").css("top" , "60px");
				}
			} else if ("fixed" == $movableDiv.css("position")) {
				$movableDiv.css("position", "absolute").css("top", topstart);
			}
		});
	};
})( jQuery );


$(function() {
// j i k - nawigacja
    function scroll(obj,direction) {
        var scrolli, i,
		positions = [],
		here = $(window).scrollTop();
		obj.each(function() {
            positions.push(parseInt($(this).offset().top,10));
        });

        for(i = 0; i < positions.length; i++) {
            if (direction == 'next' &&  positions[i] > here ) {break;}
            if (direction == 'prev' && i > 0 && positions[i] >= here) {i--;break;}
        }

		if ( here > positions[positions.length-1]) i--;

		if (i < positions.length) $("body,html").animate({"scrollTop": obj.eq(i).offset().top});

		return false;
    };

	$(document).keydown(function(e) {
		e = e ? e : window.event;

		if ('textarea' == e.target.type  || 'text' == e.target.type) {
			return;
		}

		var key = e.keyCode ? e.keyCode : e.which;

		if (75 == key) {
			scroll($('.demotivator.pic, #paginator_3000'), 'next');
		} else if (74 == key) {
			scroll($('.demotivator.pic, #paginator_3000'), 'prev');
		}
	});
});
 

function del(picId, message) {
	if (confirm("Czy na pewno chcesz NA ZAWSZE usunąć ten demotywator? Tej operacji NIE DA się cofnąć!")) {
		$.get("/demotivator/delete/"+picId, {}, function(response) {
			response = response.split(",");

			if ("delete_user" == response[1]) {
				$("#demot"+response[0]).fadeOut();
				alert("Usunięto demotywator!");
			} else if ("delete_admin" == response[1]) {
				$("#demot"+response[0]).fadeOut();
			} else if ("not_allowed" == response[1]) {
				alert("Nie masz uprawnień, by to zrobić!");
			} else if ("wrong_id" == response[1]) {
				alert("Nie ma takiego demotywatora!");
			}
		});
	}

	return false;
};


$(function() {
	var $colorpicker = $('#colorpicker');
    if ($colorpicker.length > 0) {
	    $colorpicker.farbtastic(function(color) {
			$('#colorexample').css('background-color', color);
			$('#color').val(color);
			$('#title').css("color", color);
		});
	}
});

function mod_status(id, status) {
	$.get("/demotivator/setstatus/"+id+"/"+status, {}, function(response, status) {
		if ('already_moved' == response) {
			alert('Ktoś nadał juz temu obrazkowi status '+status+'. Spróbuj zacząć moderować inną stronę.');
		} else if ('noaccess' == response) {
			alert('Nie masz uprawnień do wykonania tej akcji! Być może zostałeś wylogowany.');
		} else {
			var blinkCount = 2*2;// two blinks, 4*2 for four blinks
			do {
				$("#mod_"+response)['fade'+(0 == blinkCount%2 ? 'Out' : 'In')]('slow');
			} while (--blinkCount);
		}
	});
};


/* archiwizowanie z powodem */
function show_reason_archive_widget(id, obj) {
	//pokazuje na miejscu danej ikonki widgecik z opcją wpisania powodu archiwizacji
	var $reasonArchiveBox = $('#reason_archive_box');
	var $obj = $(obj);
	
	if ($reasonArchiveBox.is(':visible')) {
		justHide = true;
	} else {
		$reasonArchiveBox.fadeOut(0);

		var $reasonArchive = $('#reason_archive');
		$reasonArchive.find(".demotivator_id").val(id);
		$reasonArchive.find(".reason").val('');
		$reasonArchive.find(".reason_ready").val(0);

		$reasonArchiveBox.css({
//			"left": $obj.position().left - 20 + $('div#main_container').position().left,
			"left": $obj.offset().left - 20,
//			"top":  $obj.position().top  - 20 + $obj.offset().top
			"top":  $obj.offset().top - 20
		}).fadeIn("slow");
	}
};


function reason_archive_request(params) {
	//parameterki
	var id = params.id;
	var reason = params.reason;
	var reason_ready;
	if (params.reason_ready) {
		reason_ready = params.reason_ready;
	} else {
		reason_ready = 0;
	}

	//funkcje w wypadku sukcesu
	var successFunctions;
	if (params.success) {
		successFunctions = params.success;
	} else {
		successFunctions = function(data) {
			alert('sukces');
		};
	}

	//funkcje w wypadku błędu
	var errorFunctions;
	if (params.error) {
		errorFunctions = params.error;
	} else {
		errorFunctions = function(obj) {
			alert('błąd!');
		};
	}

	$.ajax({
		url: "/demotivator/setstatus/"+id+'/archiwum',
		type: 'POST',
		data: {
			reason: reason,
			reason_ready: reason_ready
		},
		success: function(data) {
			successFunctions(data);
		},
		error: function(obj) {
			errorFunctions(obj);
		}
	});
};


function reason_archive() {
	var picId = $("#reason_archive .demotivator_id").val();

	var $pic = $('#demot'+picId).removeClass('hide');

	$("span.buttons_"+picId+" input").removeAttr('disabled');

	reason_archive_request({
		id: picId,
		reason: $("#reason_archive .reason").val(),
		reason_ready: $("#reason_archive .reason_ready").val(),
		success: function(response) {
			if ("already_moved" == response) {
				alert('Ktoś już zarchiwizował ten demotywator - spróbuj zacząć moderowanie innej strony');
				$('#reason_archive_box').fadeOut();
			} else if ("noaccess" == response) {
				alert('Nie masz uprawnień, żeby to zrobić - być może zostałeś wylogowany lub ten demotywator jest na głównej');
			} else if ("error" == response) {
				alert('wystapił jakis błąd - spróbuj jeszcze raz');
			} else {
				$pic.addClass('hide');
				$('#'+picId+' .b_archiwump').attr('disabled', 'disabled');
				$('#reason_archive_box').fadeOut();
			}
		}
	});
};


/* sugestia - np. bana */
function suggest(type, demotId, link) {
	var $demot = $('#demot'+demotId).addClass('hide');
	var $link  = $(link);

	var $suggestSlider = $("#suggest_slider").css({
		'top':     $link.offset().top + 20,
		'left':    $link.offset().left - 0,
		'z-index': 100000
	})

	$suggestSlider.attr('data-id', demotId)
	$suggestSlider.attr('data-type', type);


	$("span .close", $suggestSlider).live('click', function() {
		$suggestSlider.hide();
		$demot.removeClass('hide');
	});
	$suggestSlider.show();

	$(".send", $suggestSlider).live('click', function(e) {
		e.preventDefault();

		$.post('/mod_tools/suggest/'+$suggestSlider.attr('data-type')+'/'+$suggestSlider.attr('data-id'), {
			comment: $(this).html()
		}, function(response) {
			if ('success' == response) {
				$demot.fadeOut();
			} else {
				if ('wrong_type' == response) {
					response = 'Niepoprawny typ sugestii';
				} else if ('no_id' == response) {
					response = 'Nie podałeś id';
				} else if ('doesnt_exist' == response) {
					response = 'Wybrany obrazek nie istnieje - być może został już usunięty przez administratora lub autora'
				} else if ('not_allowed' == response) {
					response = 'Nie masz uprawnień do wykonania tej akcji. Być może zostałeś wylogowany.'
				}

				alert('Wystąpił jakiś błąd! - '+response);
			}

			$demot.removeClass('hide');
			$("#suggest_slider").hide();
		});
	});

	$(".btn", $suggestSlider).live('click', function() {
		$.post('/mod_tools/suggest/'+$suggestSlider.attr('data-type')+'/'+$suggestSlider.attr('data-id'), {
			comment: $(".inpsuggest", $suggestSlider).val()
		}, function(response) {
			if ('success' == response) {
				$demot.fadeOut();
			} else {
				if ('wrong_type' == response) {
					response = 'Niepoprawny typ sugestii';
				} else if ('no_id' == response) {
					response = 'Nie podałeś id';
				} else if ('doesnt_exist' == response) {
					response = 'Wybrany obrazek nie istnieje - być może został już usunięty przez administratora lub autora'
				} else if ('not_allowed' == response) {
					response = 'Nie masz uprawnień do wykonania tej akcji. Być może zostałeś wylogowany.'
				}

				alert('Wystąpił jakiś błąd! - '+response);
			}

			$demot.removeClass('hide');
			$suggestSlider.hide();
		});
	});

};


//sekcje specjalne - moderowanie
function section_status(id, status) {
	$.get("/section_moderator/setstatus/"+id+"/"+status, {}, function(data) {
		if ('noaccess' == data) {
			alert('Nie masz uprawnień do tej akcji - być może zostałeś wylogowany');
		} else if ('error' == data) {
			alert('Wystapił błąd - spróbuj ponownie za kilka chwil');
		} else {
			var blinkCount = 6*2;// two blinks, 4*2 for four blinks
			do {
				$("#sekcja_"+data)['fade'+(blinkCount%2==0?'Out':'In')]('slow');
			} while (--blinkCount);
		}
	});
};


// Wybór rodzaju pagerowania
$(function() {
	var $pagerFull  = $('#pager_full');
	var $pagerShort = $('#pager_short');

	if ('1' == $.cookie('pagersize')) {
		$pagerFull.hide();
		$pagerShort.show();
	}

	$('#przelacznik_pagera a').click(function() {
		if ('1' == $.cookie('pagersize')) {
			$pagerFull.show();
			$pagerShort.hide();
			$.cookie('pagersize', null); // usuń
		} else {
			$pagerShort.show();
			$pagerFull.hide();
			$.cookie('pagersize','1', {expires: 255});
		}
	});
});


// prosty modal dialog, który blokuje interakcję podczas ładowania / zmiany parametrów / pisania
//wymaga kodu, ktory jest template.php
function waitDialogToggle() {
	var $modWin = $("#modWin");
	var $overlay = $('#overlay');

	if ($overlay.is(':visible')) {
		$modWin.fadeOut(function() {
			$overlay.fadeOut();
		});
	} else {
		$overlay.fadeIn(function() {
			$modWin.fadeIn();
		});
	}
};


function thisMovie(movieName) {
     if (-1 != navigator.appName.indexOf("Microsoft")) {
			return window[movieName];
     } else {
			return document[movieName];
		}
};


/**
 * Funkcje do votowania
 */
var wyniczek_flash_id = 0;
var wyniczek_flash_status = '';

function flash_result(data, textStatus) {
	wyniczek_flash_status = textStatus;
	wyniczek_flash_id = data;
};

var vote_object;
var vote_redirect;

function votowanie(object, redirect) {
	var $object = $(object);
	vote_object = $object;
	vote_redirect = redirect;

	if (false == logged_in) {
		var picId = 0;
		var urls = $object.attr('href').split('/');

		for (var i in urls) {
			if (!isNaN(urls[i])) {
				picId = urls[i];
			}
		}

		try {
			thisMovie("voteMovie").glosik(picId, $object.attr('href'));
		} catch(err) { //cos nie wyszlo z flash wiec zwroc klasyczny myk do logowania
			vote_redirect = '';//nie idz nigdzie dalej skoro glosowanie nie wyszlo
			
			try{
				vote_result('login', 'success');
			}catch(error){
				if('login' == error.response){
					loginbox($(object).parents('.voting'), '/'+picId)
				}
			}
			
			return false;
		}

		return false;
	} else {
		$.get($object.attr('href'), {}, function(response, textStatus) {
			vote_result(response, textStatus);
		});
	}

	return false;
};


function vote_result(response, textStatus) {
	var o = vote_object;

	if (null != response && "" != response) {
		if ("undefined" !== typeof vote_redirect && '' != vote_redirect) {
			window.location.href = vote_redirect;
		}

		// łapiemy tu błąd,
		// który czasem się pojawia i objawia dziwnych znaczkach na stronie
		if (response.length > 256) {
			return;
		}

				var res = response.split(",");

		//w pierwszym argumencie przechwytujemy akcje - vote albo truevote
		var action = res[0];

		var $parent = $(o).parent();

		var voteArg = ('truevote' == action)
			? 2   // jesli przesylamy paczke z true_vote
			: 4;  // jesli przesylamy paczke z votem zwykłym lub komentarzem


		if ('comment' == action) {
			$parent.find(".points").html(res[2]);
			$parent.find(".count").html(res[3]);
		} else if ('vote' == action) {
			if (res[5]) {
				$parent.find(".upvotes").html('+'+res[5]);
			}
			if (res[3]) {
				$parent.find(".count").html(' ('+res[3]+')');
			}
		} else {
			throw {
				message:     'nieprawidłowy rodzaj akcji',
				action:      action,
				vote_object: vote_object,
				$parent:     $parent,
				response:    response,
				res:         res
			};
		}


		var txt = '';

		if ('change' == res[voteArg]) {
			txt = 'Zmieniono głos!';
		} else if ('del' == res[voteArg]) {
			txt = 'Usunięto głos!';
		} else if ('new' == res[voteArg]) {
			txt = 'Dzięki!';
		} else if ('already_voted' == res[voteArg]) {
			txt = 'Już głosowałeś!';
		} else if ('not_allowed' == res[voteArg]) {
			txt = 'Nie możesz tego zrobić';
		} else if ('owner' == res[voteArg]) {
			txt = 'Nie możesz głosować na swoje dzieło'
		} else if ('login' == res[voteArg]) {
			txt = 'Zaloguj się najpierw';
		} else if ('owner' == response) {
			txt = 'Nie możesz głosować na swoje dzieło'
		} else if ('login' == response) {
			txt = '<a href="/login">Zaloguj się najpierw</a>';
		} else if ('no_access' == response) {
			txt = 'Wymagany przynajmniej jeden demotywator na głównej';
			voteArg = 2;
		} else if ('voted_removed') {
			txt = 'Obiekt, na który próbujesz zagłosować, został usunięty.';
		}

		var $pic = $parent.parent();

		var $voteResult = (2 == voteArg)
			? $parent.find(".true_vote_result")
			: $pic.find(".vote_result");

		$voteResult.html(" "+txt+" ").fadeIn("slow");
	} else {
		//alert('nodata!');
	}

	return false;
}; // eo vote_result()


// KONKURSY
function contest_vote(contest_item_id, value, object) {
	if ('simple_voting' == vote_type) {
		save_cookie(first_item, $(".contest_item_"+contest_item_id).attr('id').substr(5));
	}

	if (false == logged_in) {
		loginbox($(object));

		return false;
	}

	var $modWin = $("#modWin")


	if (   ((  'up' == value) && (  votes_up_left <= 0))
		|| (('down' == value) && (votes_down_left <= 0))
	) {
		$modWin.html('<span class="red">Nie masz już więcej głosów</span>').fadeIn();

		setTimeout(function() {
			$modWin.fadeOut(1000);
		}, 2000);

		return false;
	}



	komunikat_glosowania = setTimeout(function() {
		$modWin.html('Głosowanie… <img src="/res/img/loading.gif" />').fadeIn();
	}, 1500);

	unbindkeys();

	if (last_cliked_id != contest_item_id) {
		last_cliked_id = contest_item_id;

		$.get('/contest/vote_add/' + contest_item_id + '/' + value, {}, function(response) {
			clearTimeout(komunikat_glosowania);

			var res = response.split("|");
			var txt = '';

			if (res[0] == 'flood')
				txt = 'Oddałeś za dużo głosów w ostatnim czasie';
			if (res[0] == 'incorrect_vote_value')
				txt = 'Niepoprawna wartość głosu';
			else if (res[0] == 'contest_item_does_not_exist')
				txt = 'Wybrane zgłoszenie nie istnieje';
			else if (res[0] == 'owner')
				txt = 'Nie możesz głosować na swoje zgłoszenie, wybierz inne';
			else if (res[0] == 'banned')
				txt = 'Nie możesz głosować, bo jesteś zbanowany';
			else if(res[0] == 'already_voted')
				txt = 'Już głosowałeś na ten podpis';
			else if(res[0] == 'wrong_vote_time')
				txt = 'Nie możesz teraz głosować';
			else if(res[0] == 'votes_limit')
				txt = 'Wykorzystałeś już limit tego typu głosów';
			else if(res[0] == 'not_logged')
				txt = 'Nie jesteś zalogowany';
			else if(res[0] == 'participate_in_contest')
				txt = 'Nie możesz głosować w konkursie, w którym brałeś udział';
			else if (res[0] == 'success') {
				txt = 'Poprawnie oddano głos';

				if ('down' == value) {
					$('#votes_down_left .votes_value').html(--votes_down_left);
				}

				if ('up' == value) {
					$('#votes_up_left .votes_value').html(--votes_up_left);
				}
			}

			$(".contest_item_"+contest_item_id+" .contest_infobar").html(txt);

			//jak zgłoszenie nie istnieje, to znaczy, że jest jeszcze w cache'u i można je zignorować
			if ('success' == res[0] || 'contest_item_does_not_exist' == res[0]) {
				$modWin.fadeOut(0);

				if ('only_one' == vote_type) {
					next_item();
				}
			} else {
				$modWin.html('<span class="red">' + txt + '</span>').fadeIn();

				setTimeout(function() {
					$modWin.fadeOut(1000);
				}, 2000);
			}

			bindkeys();
			last_cliked_id = 0;
		});
	}

	return false;
};


function is_logged(link) {
	if (false == logged_in) {
		loginbox(link);

		return false;
	}

	return true;
};

function change_page(id) {
	$(".contest_site").fadeOut(0);
	$("#site_"+id).fadeIn(1000);
	return true;
};

function change_contest_item(id) {
	$(".d_mainthumb_description").fadeOut(0);
	$("#item_"+id).fadeIn(1000);
	return false;
};

/**
* Funkcja zapisuje wartosc aktualnie przegladanego zgloszenia do ciastka
*/
function save_cookie(first_id, item_id) {
	var date = new Date();
	date.setTime(date.getTime() + (24 * 60 * 60 * 1000));
	$.cookie(cookie, first_id+"|"+item_id, {path: '/', expires: date});
};


/**
 * Inicjalizuje pierwsze wyświetlane zgłoszenie
 */
function read_cookie() {
	var cookie_values = $.cookie(cookie);

	if (null == cookie_values) {
		current_item = roll();

		while (('deleted' == $("#item_"+current_item+" .item_status").html())
			/*|| ($("#item_"+current_item+" .user_id").html() == user_id)*/
		) {
			current_item++;
			if (current_item == count) {
				current_item = 1;
			}
		}

		save_cookie(current_item, current_item);
		cookie_values = $.cookie(cookie);
	}

	var res = cookie_values.split('|');

	current_item = res[1];
	first_item = res[0];
	last_item = first_item;

	do {
		last_item--;
		if (last_item == 0) {
			last_item = count;
		}
	} while (  ('deleted' == $("#item_"+last_item+" .item_status").html())
			/*|| ($("#item_"+last_item+" .user_id").html() == user_id)*/
	);

	item_position_info()
	check_buttons();

	if (('deleted' == $("#item_"+current_item+" .item_status").html())
		/*|| ($("#item_"+current_item+" .user_id").html() == user_id)*/
	) {
		next_item();
		return false;
	}

	change_contest_item(current_item);
};


/**
* Funkcja sprawdza aktywność przycisków
*/
function check_buttons() {
	if (first_item == current_item){
		$('#button_next').fadeOut(0);
	} else if (0 == $('#button_next:visible').length) {
		$('#button_next').fadeIn();
	}

	if (current_item == last_item) {
		$('#button_previous').fadeOut(0);
	} else if (0 == $('#button_previous:visible').length) {
		$('#button_previous').fadeIn();
	}
};


/**
* Losuje pierwszy wyswietlony demot
*/
function roll() {
	return Math.floor(count*Math.random() + 1);
};

/**
* Pokazuje następne zgłoszenie w kolejności
*/
function next_item() {
	var $modWin = $("#modWin");

	if (current_item == last_item) {
		$modWin.html(
			'<span class="red">'+
				'Hej, przejrzałeś już wszystkie zgłoszenia, dziękujemy za uwagę'+
			'</span>'
		).fadeIn();

		setTimeout(function() {
			$modWin.fadeOut(1000);
		}, 3000);

		return false;
	}

	if (current_item >= count) {
		current_item = 1;
	} else {
		current_item = Number(current_item) + 1;
	}

	if (/*($("#item_"+current_item+" .user_id").html() == user_id) || */($("#item_"+current_item+" .item_status").html() == 'deleted')){
		next_item();
		return false;
	}

	save_cookie(first_item, current_item);
	change_contest_item(current_item);

	$modWin.fadeOut();

	check_buttons();
	item_position_info()

	return false;
};

/**
 * Pokazuje poprzednie zgłoszenie w kolejności
 */
function previous_item() {
	if (current_item == first_item) {
		return false;
	}

	if (current_item <= 1) {
		current_item = count;
	} else {
		current_item = Number(current_item) - 1;
	}

	if (/*($("#item_"+current_item+" .user_id").html() == user_id) || */($("#item_"+current_item+" .item_status").html() == 'deleted')){
		previous_item();
		return false;
	}

	save_cookie(first_item, current_item);
	change_contest_item(current_item);

	$("#modWin").fadeOut();

	check_buttons();
	item_position_info()

	return false;
};

/**
* Update pozycji zgłoszenia
*/
function item_position_info() {
	if (Number(current_item) >= Number(first_item)){
		real_current_item = (Number(current_item) - Number(first_item))+1;
	}else{
		real_current_item = ((Number(count) - Number(first_item)) + Number(current_item))+1;
	}
	votes_information = "Przeglądasz zgłoszenie "+real_current_item+" z "+count;
	$('#votes_info').html(votes_information);
};


function bindkeys() {
	//jQuery(document).bind('keydown', 'a',function (evt){previous_item(); return false; });
	//jQuery(document).bind('keydown', 'd',function (evt){next_item(); return false; });
	//jQuery(document).bind('keydown', 'w',function (evt){contest_vote($(".d_mainthumb_description:visible .item_id").html(), "up"); return false; });
	//jQuery(document).bind('keydown', 's',function (evt){contest_vote($(".d_mainthumb_description:visible .item_id").html(), "down"); return false; });
};

function unbindkeys() {
	$(document).unbind('keydown', 'a', function (e) {
		previous_item();
		return false;
	});
	$(document).unbind('keydown', 'd', function (e) {
		next_item();
		return false;
	});
	$(document).unbind('keydown', 'w', function (e) {
		contest_vote($(".d_mainthumb_description:visible .item_id").html(), "up");
		return false;
	});
	$(document).unbind('keydown', 's', function (e) {
		contest_vote($(".d_mainthumb_description:visible .item_id").html(), "down");
		return false;
	});
};

/**
 * Ukrywa menu głosowania
 */
function hide_buttons(){
	$('#contest_voting_box').fadeOut(0);
};

/**
 * Zamykanie konkursu bez zwycięzcy
 *
 * @param integer contest_id
 */
function close_without_winner(contest_id) {
	if (confirm('Na pewno chcesz zakończyć ten konkurs bez zwycięzcy?')) {
		$.getJSON("/contest_admin/close_without_winner/"+contest_id, {}, function(response) {
			if ("success" == response.result) {
				window.location = "/contest_admin/index"
			} else if ("error" == response.result) {
				alert('Wystapił błąd! - '+response.errors);
			}
		});
	}
};


//Odpowiednik phpowej funkcji w helperze word
function replace_number(number, words) {
	var word = words.split("|");
	//0 - taki demtywator
	//1 - takie demotywatory
	//2 - takich demotywatorów
	var abs_number = Math.abs(number);

	if (1 == abs_number) {
		return number+word[0];
	} else if (
		(
			(abs_number > 1) &&
			(abs_number < 5)
			)
		||
		(
			(abs_number > 21) 		&&
			((abs_number % 10) >= 2) &&
			((abs_number % 10) <= 4) &&
			((abs_number % 100) >= 20)
			)
	) {
		return number+word[1];
	} else{
		return number+word[2];
	}
};


// REPORTS.js

$('.reportButton').live('click', function(e){
	var $self = $(this);
	var type = $self.attr('data-type');
	var id = $self.attr('data-id');
	
	var $report_form = $("#report_"+type);

	if (($("#item_id_"+type).val() == id) && ($("#report_" + type +":visible").length > 0 ) ) {
		var justHide = true;
	}

	if (!justHide) {
		$report_form.hide(0);
	} else {
		$report_form.fadeOut("slow");
	}

	$("#item_id_"+type).val(id);
	$report_form.css("left", ($self.position().left + 20));
	$report_form.css("top", $self.offset().top + 15);

	if (!justHide) {
		$report_form.fadeIn("slow");
	}
	e.preventDefault();
});

function inpmodified(obj) {
	$(obj).addClass("modified");
};

function inpclear(obj) {
	var $obj = $(obj);
	if (!$obj.hasClass("modified")) {
		$obj.val('');
	}
};

function repredirect(repres, type) {
	var id = $("#item_id_"+type).val();
	location.href = "/contact/"+repres+"/"+id;
};


function reportsubmit(repres, type) {
	var $reportComment = $("#reportcomment_"+type);

	if (!$reportComment.hasClass("modified")) {
		$reportComment.val('');
	}

	if ('spam' != repres) {
		var comm = prompt('Jeśli chcesz, możesz podać dodatkowe informacje - np link do oryginalnego demota, itp.', '');

		if (null === comm) {
			return false;
		}
	}

	$reportComment.val(comm);
	$("#reportreason_"+type).val(repres);

	var $form = $("#report_"+type+" form");

	$.post($form.attr("action"), $form.serialize(), function(response) {
		if (response) {
			var res = response.split("|");

			if ("user_demotivator" == res[0]) {
				$("#link_"+type+"_"+res[1]).replaceWith("Nie możesz zgłaszać swojego obrazka");
				$("#report_"+type).hide("slow");

				return false;
			}

			if ("user_comment" == res[0]) {
				$("#link_"+type+"_"+res[1]).replaceWith("Nie możesz zgłaszać swojego komentarza");
				$("#report_"+type).hide("slow");

				return false;
			}

			$("#link_"+type+"_"+response).replaceWith("Zgłoszenie przyjęte!");
			$("#report_"+type).hide("slow");
		}
	});

	$("#reportform").submit();
}; // eo reportsubmit()


function report_duplicate(link, id) {
	if (false == logged_in) {
		loginbox(link);
		return false;
	}

	if (confirm("Czy na pewno chcesz zgłosić ten demotywator, jako duplikat?")) {
		var comm = prompt('Jeśli chcesz, możesz podać dodatkowe informacje - np link do oryginalnego demota, itp.', '');

		$.get("/report/duplicate/"+ id + "/" +  $.base64Encode(comm), {}, function(data) {
			if (data == "success") {
				$("#duplicate_demotivator_"+id).replaceWith("Zgłoszenie przyjęte!");
			} else if (data == "wrong_id") {
				alert("Złe id!");
			} else if (data == "not_exist") {
				alert('Ten demotywator nie istnieje. Być może ktoś go w tzw. "międzyczasie" usunął?');
			} else if (data == "database_error") {
				alert("Z jakiegoś powodu nie można zaraportować tego demotywatora.");
			} else if (data == "already_reported") {
				$("#duplicate_demotivator_"+id).replaceWith("Już raportowałeś ten demotywator!");
			} else if ("equal_user_id" == data) {
				$("#duplicate_demotivator_"+id).replaceWith("Nie możesz raportować swojego demotywatora!");
			} else if ("not_logged" == data) {
				alert("Nie jesteś zalogowany.");
			}
		});

		return false;
	}
}; // eo report_dupliacte()


//ULUBIONE
$(function() {
	$("a.favorite").click(function() {
		if (false == logged_in) {
			loginbox(this);

			return false;
		}

		var message;
		var $o = $(this);
		var $parent = $o.parent();

		$.get($o.attr('href'), {}, function(response, textStatus) {
			var res = response.split(",");

			if ('success' == textStatus) {
				if (res[0] == 'dodano') {
					message = 'Dodano do ulubionych';
					$o.text("Usuń");
					$o.attr('href','/index.php/user/delete_favorite/'+res[1]);
				} else if ('usunieto' == res[0]) {
					message = 'Usunięto z ulubionych';
					$o.text("Dodaj");
					$o.attr('href','/index.php/user/add_favorite/'+res[1]);

					if (1 == moje_ulubione) {
						$("#demot"+res[1]).fadeOut();
					}
				} else if ('istnieje' == res[0]) {
					message = 'Istnieje w ulubionych';
					$o.text("Usuń");
					$o.attr('href','/index.php/user/delete_favorite/'+res[1]);
				} else if ('nie_istnieje' == res[0]) {
					message = 'Nie istnieje w ulubionych';
				} else if ('brak_demota' == res[0]) {
					message = 'Brak demota o podanym ID';
				} else if ('niezalogowany' == res[0]) {
					message = 'Zaloguj się';
				} else if ('brak_danych' == res[0]) {
					message = 'Brak wszystkich danych (id demota?)';
				} else {
					message = response;
				}

				$(".vote_result", $parent)
					.html(" "+message+" ")
					.fadeIn("slow");

			} else {
				$(".vote_result").text("Błąd skryptu");
			}
		});

		return false;
	});
});


/**
 * Pokazuje okienko logowania.
 *
 * @param link  element wobec, którego będziemy pozycjonować boksa
 * @param url   adres na który ma nastąpić redirect po zalogowaniu
 */
function loginbox(link, url) {
	var $loginbox = $("#loginbox");
	
	if('object' == typeof link){
		$link = link;
	}else{
		var $link = $(link);
	}
	
	if (!$loginbox.is(":visible")) {
		$loginbox.fadeOut(0);

		// jeśli przekazujemy drugi parametr,
		// to jest to url,
		// na ktory ma przekierowac po zalogowaniu
		if (undefined != url) {
			$('#login_redirect').val(url);
		}

		$("h2", $loginbox).html(
			'<div style="float:left">Logowanie</div>'+
			'<div style="float:right">'+
				'<a href="#" onclick="close_loginbox(); return false;">X</a>&nbsp;'+
			'</div>');

		$(".loginbox_message", $loginbox).text('Aby to zrobić zaloguj się.');

		$(".demotivator", $loginbox).css({
			'width':      '450px',
			'margin-top': '30px'
		});

		$("#log_in").css({
			'margin-left':  '0px',
			'padding-left': '10px',
			'color':        '#FFFFFF'
		});

		$loginbox.fadeIn("slow");
	}
}; // eo loginbox()


function close_loginbox() {
	$("#loginbox").fadeOut("slow");
};


/**
 * Pokazuje standardowe okienko komunikatu
 *
 * @param string   message  treść wiadomości
 * @param integer  time     czas trwania wiadomości w ms
 */
var standard_message = false;
function show_standard_message(params) {
	if ('undefined' == typeof(params)) {
		throw 'params required';
	}

	var message = params.message;
	var hide_time = params.hide_time;

	if (!message) {
		throw "message required";
	}

	//standardowy czas trwania to 4 sekundy, jesli ktos nie poda
	if ('undefined' == typeof(hide_time)) {
		hide_time = 4000;
	}

	//wyświetlamy komunikat
	$("#overlay").fadeIn();
	$("#modWin").html(message).fadeIn();

	//jeśli ustawiono czas, to chowamy komunikat po wskazanym czasie
	if (hide_time > 0) {
		clearTimeout(standard_message);
		standard_message = setTimeout(function() {
			hide_standard_message();
		}, hide_time);
	}
};


/**
 * Chowa standardowe okienko z informacją
 */
function hide_standard_message() {
	$("#modWin").fadeOut();
	$("#overlay").fadeOut();
};


/**
 * Skrócona forma show_standard_message
 */
function __msg(message, time) {
	show_standard_message({
		message: message,
		hide_time: time
	});
};


/**
 * Skrócona forma hide_standard_message
 */
function __hmsg() {
	hide_standard_message();
};


function showbuttons() {
	var address = window.location.href;
	var pos = address.split("#");

	if (null != pos[1]) {
		setTimeout(function() {
			location.hash = pos[1];
		}, 1000);
	}

	if (user_id > 0) {
		$(".reply_button").show();
	}
};


//myspace
function GetThis(T, C, U, L) {
	var targetUrl = 'http://www.myspace.com/index.cfm?fuseaction=postto&' + 't=' + encodeURIComponent(T)
	+ '&c=' + encodeURIComponent(C) + '&u=' + encodeURIComponent(U) + '&l=' + L;
	window.open(targetUrl);
};


function dmail(){
	var $dmail = $("span#dmail");
	var messagesCount = $.cookie('demotywatory_pms_'+user_id);

	if (messagesCount > 0) {
		$dmail.html('<a id="pms_link" href="/dmail" class="pm_blink">Masz wiadomość (<span id="pms_num">'+messagesCount+'</span>)</a>');
	} else if (null != messagesCount) {
		$dmail.html('<a id="pms_link" href="/dmail">Prywatne wiadomości</a>');
	} else if (user_id > 0) {
		$.get("/message/check_num", {}, function(response) {
			var date = new Date();
			date.setTime(date.getTime() + (5 * 60 * 1000));

			$.cookie('demotywatory_pms_'+user_id, response, {
				path: '/',
				expires: date
			});

			if (response > 0) {
				$dmail.html('<a id="pms_link" href="/dmail" class="pm_blink">Masz wiadomość (<span id="pms_num">'+response+'</span>)</a>');
			} else {
				$dmail.html('<a id="pms_link" href="/dmail">Prywatne wiadomości</a>');
			}
		});
	}
};


//dodawanie do obserwowanych
function observe(username, action, div_sufix){
	$.get('/obserwuj/'+username+'/'+action , {}, function(response) {
		if (response == 'saved') {
			$("#obs_info_" + div_sufix).text("Dodano do obserwowanych");
		} else if ('observed' == response) {
			$("#obs_info_" + div_sufix).html('Już obserwujesz tego użytkownika. <a href="javascript:void(0)" onClick="observe(\''+username+'\',\'remove\',\''+ div_sufix +'\')">[ usuń z obserwowanych ]</a>');
		} else if ('removed' == response) {
			$("#obs_info_" + div_sufix).html('Usunięto z obserwowanych');
		} else {
			alert('Wystąpił błąd');
		}
	});
};


//Formularz rejestracyjny
$(function() {
	$('#username').change(function() {
		var $user_exists = $("#user_exists");
		if ($user_exists.length > 0) {
			$user_exists.remove();
			$("input#rejestruj").removeAttr("disabled");
		}
	});
});

var check;
/**
* Reguluje czasowe wywolywanie funkcji check_username przy wstukiwaniu klawiszy
*/
function check_login() {
	clearTimeout(check);
	check = setTimeout(function() {
		check_username();
	}, 2000);
};

/**
 * Sprawdza, czy podany login jest dostępny
 */
function check_username() {
	clearTimeout(check);

	$('#username_check').remove();

	var $username = $('#username');

	$username.after('<span id="username_check" class="red"><img src="/res/img/loading2.gif" /></span>');

	var login = $username.val();

	var $usernameCheck = $('#username_check');

	if (login.length < 3) {
		$usernameCheck.html('Za krótki');
	} else {
		$.getJSON("/user/correct_username/"+login, {}, function(response) {
			if (response.success) {
				$usernameCheck.html('<img src="/res/img/icons/correct.png" />');
			} else if ('username_already_exists' == response.error) {
				$usernameCheck.html('Zajęty');
			} else {
				$usernameCheck.html('Niepoprawny');
			}
		});
	}
};


/**
 * Funkcja wykonuje akcję wskazaną w parametrze
 * @param action
 * @return bool
 */
function action_after(action) {
	if (jQuery.isFunction(action)) {
		action();
	} else {
		var action_array = action.split('|');

		if ('delete_suggests' == action_array[0]) {
			delete_suggests(action_array[1], action_array[2], action_array[3])
		} else if ('close_demotivator_report' == action_array[0]) {
			$('#report_demot_'+action_array[1]).fadeOut();
		}
	}
};


/**
 * Badziewie do sekcji specjalnych
 * Pobiera demotywatory sekcji do wyświetlenia w głosowaniu
 */
function RandomGallery(array) {
	var self = this;

	this.demotivatorsList = array.demotivatorsList,
	this.section_id = array.section_id,
	this.info_place = array.info_place,
	this.gallery_place = array.gallery_place,
	this.per_page = array.per_page,
	this.display_vote_menu = true,
	this.demotivatorsListPage = null,
	this.baseHref = array.baseHref,
	this.type = array.type,
	this.getDemotivatorsListUrl = array.getDemotivatorsListUrl,

	this.list_template = false,
	this.single_template = false,
	this.paginator_template = false,

	this.getDemotivatorsList = function(){
		$.ajax({
			url: self.getDemotivatorsListUrl,
			cache: false,
			beforeSend: function(){
				self.info_place.html('<img src="/res/img/loading2.gif" ALT="" align="absmiddle"> Ładowanie...');
			},
			success: function(data){
				var data = eval('('+data+')');
				self.display_vote_menu = data.display_vote_menu;
				switch (self.type){
					case 'chronological':
						self.demotivatorsList = self.shuffle(data.demotivators_list);
						break;
					case 'best':
						self.demotivatorsList = data.demotivators_list;
						break;
				}

				self.draw(1);
			},
			error: function(data){
				try{
					data = eval('('+data.responseText+')');
				}catch(exception){
					data = false;
				}
				var error;
				if (data !== false){
					if (data.error.user == 'havent_permission'){
						error = 'Nie masz uprawnień aby zobaczyć te wyniki';
					}else{
						error = 'Nieobsługiwany błąd';
					}
				} else {
					error = 'Server napotkał nierozpoznany błąd!';
				}
				self.info_place.html(error);
			}
		});
	},
	/**
	 * pobiera szablon strony i uzupełnia demotami
	 */
	this.draw = function(page_num){
		//Jesli nie ma szablonow, to je pobieramy
		if (!self.list_template || !self.single_template || !self.paginator_template){
			$.ajax({
				url: '/section/get_gallery_template/'+self.section_id,
				cache: false,
				beforeSend: function(){
					self.info_place.html('<img src="/res/img/loading2.gif" ALT="" align="absmiddle"> Ładowanie...');
				},
				success: function(data){
					var data = eval('('+data+')');
					self.list_template = $.base64Decode(data.list);
					self.single_template = $.base64Decode(data.single);
					self.paginator_template = $.base64Decode(data.paginator);
					self.completeTemplates(page_num);
				},
				error: function(data){
					try{
						data = eval('('+data.responseText+')');
					}catch(exception){
						data = false;
					}
					var error;
					if (data !== false){
						if (data.error.section == 'doesnt_exist'){
							self.info_place.html('Podana sekcja nie istnieje');
						}
						if (data.error.section){
							switch (data.error.section){
								case 'list_doesnt_exist':
									self.info_place.html('Nie odnalazłem widoku listy');
									break;
								case 'single_doesnt_exist':
									self.info_place.html('Nie odnalazłem widoku pojedynczego demotywatora');
									break;
								case 'paginator_doesnt_exist':
									self.info_place.html('Nie odnalazłem widoku paginatora');
									break;
							}
						}
						error = data.error;
					}else{
						error = 'Server napotkał nierozpoznany błąd!';
					}
					self.info_place.html(error);
				}
			});
		}else{
			self.completeTemplates(page_num);
		}
	},
	/**
	 * wypełnia szablony odpowiednim kodem
	 */
	this.completeTemplates = function(page_num) {
		var demotivators_content = '';
		var start = (self.per_page * (page_num-1))
		var stop = start+10;
		self.demotivatorsListPage = self.demotivatorsList.slice(start, stop);
		for (var i in self.demotivatorsListPage){
			var complete_single_template;
			{
				complete_single_template = self.single_template;
				complete_single_template = complete_single_template.replace(/%title%/g, self.demotivatorsListPage[i].title);
				complete_single_template = complete_single_template.replace(/%text1%/g, self.demotivatorsListPage[i].text1);
				complete_single_template = complete_single_template.replace(/%text2%/g, self.demotivatorsListPage[i].text2);
				if (self.demotivatorsListPage[i].user.username == -1){
					complete_single_template = complete_single_template.replace(/%username%/g, '');
				}else{
					complete_single_template = complete_single_template.replace(/%username%/g, 'przez <a href="/user/'+self.demotivatorsListPage[i].user.username+'">'+self.demotivatorsListPage[i].user.username+'</a>');
				}
				complete_single_template = complete_single_template.replace(/%filename%/g, self.demotivatorsListPage[i].filename);
				complete_single_template = complete_single_template.replace(/%id%/g, self.demotivatorsListPage[i].id);
				complete_single_template = complete_single_template.replace(/%mainthumb%/g, self.demotivatorsListPage[i].mainthumb);
				if (self.demotivatorsListPage[i].source)
					complete_single_template = complete_single_template.replace(/%source%/g, "Źródło: "+self.demotivatorsListPage[i].source);
				else
					complete_single_template = complete_single_template.replace(/%source%/g, "");
				complete_single_template = complete_single_template.replace(/%dateadded%/g, self.demotivatorsListPage[i].dateadded);
				complete_single_template = complete_single_template.replace(/%height%/g, self.demotivatorsListPage[i].height);
				if (!self.display_vote_menu){
					complete_single_template = complete_single_template.replace(/%voting%/g,
					' Punkty: '+
					' <span class="points">'+self.demotivatorsListPage[i].total_votes+'</span><span class="count"></span> '+
					' <span class="vote_result">Głosowanie zakończone</span>');
				}else if (self.demotivatorsListPage[i].total_votes == -1 && self.demotivatorsListPage[i].total_points == -1){
					complete_single_template = complete_single_template.replace(/%voting%/g,
					' Głosuj: '+
					' <a href="/demotivator/vote/'+self.demotivatorsListPage[i].id+'/up" onclick="votowanie(this, location.href); return false;" class="vote voteup iconlik">mocne</a> '+

					' <a href="#" class="report_duplicate" id="duplicate_demotivator_'+self.demotivatorsListPage[i].id+'" onclick="report_duplicate(\'\', \''+self.demotivatorsListPage[i].id+'\'); return false">było</a> '+
					' Punkty: '+
					' <span class="points"></span><span class="count"></span> '+
					' <span class="vote_result">Zagłosuj, zobaczysz ocenę</span> ');
					//complete_single_template = complete_single_template.replace(/%points%/g, '');
					//complete_single_template = complete_single_template.replace(/%count%/g, '');
					//complete_single_template = complete_single_template.replace(/%vote_result%/g, 'Zagłosuj, zobaczysz ocenę');
				}else{
					complete_single_template = complete_single_template.replace(/%voting%/g,
					' Głosuj: '+
					' <a href="/demotivator/vote/'+self.demotivatorsListPage[i].id+'/up" onclick="votowanie(this, location.href); return false;" class="vote voteup iconlik">mocne</a> '+

					' <a href="#" class="report_duplicate" id="duplicate_demotivator_'+self.demotivatorsListPage[i].id+'" onclick="report_duplicate(\'\', \''+self.demotivatorsListPage[i].id+'\'); return false">było</a> '+
					' Punkty:'+
					' <span class="points">'+self.demotivatorsListPage[i].total_points+'</span> <span class="count"></span> '+
					' <span class="vote_result"></span> ');
					//complete_single_template = complete_single_template.replace(/%points%/g, self.demotivatorsListPage[i].total_votes);
					//complete_single_template = complete_single_template.replace(/%count%/g, ' ('+self.demotivatorsListPage[i].total_points+')');
					//complete_single_template = complete_single_template.replace(/%vote_result%/g, '');
				}

			}
			//doklejamy na koniec listy nowego demota;
			demotivators_content += complete_single_template;
		}
		//paginatorek
		var complete_paginator_template = self.paginator_template;
		var pages_count = Math.floor(self.demotivatorsList.length / self.per_page)+1*(Number(Boolean((self.demotivatorsList.length%self.per_page))));
		complete_paginator_template = complete_paginator_template.replace("%pages_count%", pages_count);
		complete_paginator_template = complete_paginator_template.replace("%per_page%", 40);
		complete_paginator_template = complete_paginator_template.replace("%current_page%", page_num);
		complete_paginator_template = complete_paginator_template.replace("%site_url%", self.baseHref+'/page/');

		var complete_list_template = self.list_template;

		complete_list_template = complete_list_template.replace('%demotivators%', demotivators_content);
		complete_list_template = complete_list_template.replace('%paginator%', complete_paginator_template);

		self.info_place.html('');
		self.gallery_place.html(complete_list_template);
		$("a.favorite").bind('click', function(){
			add_to_favorite(this, location.href);
			return false;
		});
		$('#paginator_3000 a').bind('click', function(){
			var target_page_num = $(this).html();
			self.draw(target_page_num);
			location.href = self.baseHref+'#section';
			location.href = self.baseHref+'#/page/'+target_page_num;
			return false;
		});
		$('body').bind('mouseup', function(){
			$('#paginator_3000 a').bind('click', function(){
				var target_page_num = $(this).html();
				self.draw(target_page_num);
				location.href = self.baseHref+'#section';
				location.href = self.baseHref+'#/page/'+target_page_num;
				return false;
			});
		});
	},
	/**
	 * zwraca pomieszaną tablicę z demotami
	 */
	this.shuffle = function(array){
		var seed = self.getRandomSeed();
		seed = seed%array.length;
		var suffix = array.splice(seed);
		array = suffix.concat(array);
		return array;
	},
	/**
	 * zwraca ziarenko losowosci na podstawie ktorego miksujemy liste demotow
	 */
	this.getRandomSeed = function(){
		var seed = $.cookie('section_'+self.section_id+'_seed');
		if (!seed){
			seed = Math.floor(Math.random()*10000);
			$.cookie('section_'+self.section_id+'_seed', seed, {expires: 60*60*24*7});
		}
		return seed;
	}
};


$(function() {
	/**
	 * Ustalamy, że pic NIE JEST polecany:
	 */
	$(".pic_is_recommended_choice a.pic_is_recommended").click(function(e) {
		e.preventDefault();

		var $this = $(this);
		var picId = $this.parents(".pic").children(".pic_id").val();
		var picIsRecommended = 0;

		$.ajax({
			url: "/pic/set_recommended",
			type: "POST",
			data: {"pic_id": picId, "pic_is_recommended": picIsRecommended},
			dataType: 'json',
			success: function(responseJSON) {
				if (responseJSON.success) {
					$this.removeClass("selected");

					$this
						.parents(".pic_is_recommended_choice")
						.children(".pic_is_not_recommended")
						.addClass("selected");
				} else {
					$this.replaceWith("<span>Wystąpił błąd!</span>");
				}
			}, // success
			error: function() {
				info(picId, "Wystąpił nieznany błąd.");
			}
		}); // eo ajax
	});

	/**
	 * Ustawiamy, że pic JEST polecany.
	 */
	$(".pic_is_recommended_choice a.pic_is_not_recommended").click(function(e) {
		e.preventDefault();

		var $this = $(this);
		var picId = $this.parents(".pic").children(".pic_id").val();
		var picIsRecommended = 1;


		$.ajax({
			url: "/pic/set_recommended",
			type: "POST",
			data: {"pic_id": picId, "pic_is_recommended": picIsRecommended},
			dataType: 'json',
			success: function(responseJSON) {
				if (responseJSON.success) {
					$this.removeClass("selected");

					$this
						.parents(".pic_is_recommended_choice")
						.children(".pic_is_recommended")
						.addClass("selected");
				} else {
					$this.replaceWith("<span>Wystąpił błąd!</span>");
				}
			}, // success
			error: function() {
				info(picId, "Wystąpił nieznany błąd.");
			}
		}); // eo ajax
	});
});


//content bloków
$(function() {
	//bindujemy każdemu guzikowi menu akcję
	$('.multi_widget .menu .tab').each(function(key, obj) {
		var $obj = $(obj);
		var $container = $('#content_'+id);

		var id = $obj.attr('id').substr('menu_'.length);

		$obj.bind('click', function() {
			$obj.removeClass('off')
				.addClass('on')
				.siblings()
				.removeClass('on')
				.addClass('off');

			$container.removeClass('off')
				.addClass('on')
				.siblings()
				.removeClass('on')
				.addClass('off');
		});
	});
});

function fb_share(url) {
	window.open(
		"https://www.facebook.com/share.php?u="+encodeURIComponent(url)+"&src=sp",
		"shwindow",
		"menubar=0,resizable=0,width=450,height=350"
	);
	return false;
};



/**
 * Zalogowani mogą oglądać demoty z treściami dla dorosłych.
 */
$('.shad .show_button').live('click', function(e) {
	e.preventDefault();
	var $picBox = $(this).parents('.demot_pic');
	var $img = $('a img.demot', $picBox);
	$img.attr('src', $img.attr('data-src'));
	$('.shad', $picBox).remove();
});


/**
 * Przejście do strony logowania
 * z późniejszym powrotem do aktualnie przeglądanej strony.
 */
$('.loginbox_trigger').live('click', function(e) {
	e.preventDefault();

	loginbox(this, window.location.href);
});




function addComment(commentType, commentedId, parentId) {
	var $comment      = $('#comment');
	var $commentReply = $('#comment_reply');

	// komentarz nie został napisany
	if ('' == $comment.val() && '' == $commentReply.val()) {

		__msg('Musisz wpisać jakiś komentarz!', 2000);

	// napisano komentarz:
	} else {

		var newCommentContent = (parentId > 0) ? $commentReply.val() : $comment.val();


		var handleSuccess = function(response) {
			response = JSON.parse(response);

			// wypełniamy szablonik js danymi po stronie klienta
			var $newComment = $.tmpl($.base64Decode(response.template), {
				comment: response.comment,
				commentedId: commentedId,
				sessionUser: {
					username:   username,
					isLoggedIn: logged_in
				}
			});

			if (0 == parentId) {
				$('#comment_form').before($newComment);
			} else {
				var $last = $('.comment-box.child_'+parentId+':last');

				if ($last.html()) {
					$last.after($newComment)
				} else {
					//w innym wypadku doklejamy to po aktualnym komentarzu
					$('.comment-box#comment_'+parentId).after($newComment)
				}

				$(".reply_form").fadeOut().remove();
			}

			$comment.val('');

			location.hash = 'comment_'+response.comment.id;
			__hmsg();

			var $noComments = $("h2.no_comments");
			if ($noComments.is(':visible')) {
				$noComments.fadeOut();
			}
			$(".reply_button").fadeOut().remove();
		}; // eo handleSuccess();


		$.ajax({
			type: 'POST',
			url: '/comment/add/'+commentedId,
			dataType: 'JSON',
			data: {
				comment_type: commentType,
				comment:      newCommentContent,
				parent_id:    parentId
			},
			beforeSend: function() {
				__msg('Trwa dodawanie komentarza… <img src="/res/img/loading.gif" />', 0);
			},
			success: handleSuccess,
			error: function(response) {
				var data = new Array();
				var error;

				try {
					data = eval("("+response.responseText+")");

					if (!data.translatedError && data.dictionary && data.errorCode) {
						error = 'Wystąpił błąd. Kod błędu: '+data.dictionary+'.'+data.errorCode
								+'. W razie problemów wyślij go do administracji serwisu';
					}

					error = data.translatedError;
				} catch(err) {
					error = 'Wystąpił nieznany błąd, przepraszamy.';
				}

				__msg(error, 4000);
			}
		}); // eo ajax()
	}

	return false;
}; // eo addComment()


$(function() {
	$('.js-add_comment_button').live('click', function(e) {
		e.preventDefault();

		var $button = $(this);

		addComment(
			$button.attr('data-comment-type'),
			$button.attr('data-commented-id'),
			$button.attr('data-comment-parent-id')
		);
	});
});

function show_hidden_comment(commentId) {
	var $comment = $("#comment_"+commentId).slideToggle();
	var $text = $('.hidden_bar_text .show-hide-comment', $comment.prev('.hidden_bar'));
	$text.html((('pokaż' == $text.html()) ? 'ukryj' : 'pokaż'));
};


function hide_comment(commentType, commentId) {
	if (confirm('Czy na pewno chcesz usunąć ten komentarz?')) {
		$.post("/comment/hide/"+commentId, {comment_type: commentType}, function(response) {
			response = response.split("|");

			if ("success" == response[0]) {
				$(".commentbuttons_"+response[1]).hide();
				$("#comment_"+response[1]).addClass("negative");
				$("p.commcontent_"+response[1]).text("Komentarz usunięty");
			} else if ("error" == response[0]) {
				alert('Błąd podczas usuwania komentarza!');
			} else if ("not_allowed" == response[0]) {
				alert("Nie masz uprawnień, by to zrobić!");
			} else if ("wrong_id" == response[0]) {
				alert("Nie ma takiego komentarza! Być może ktoś Cię uprzedził.");
			}
		});
	}

	return false;
};

function delete_hided_comment(commentType, commentId, confirmMessage) {
	if (confirm(confirmMessage)) {
		$.post("/admin/comment/delete_hided_comment/"+commentId, {comment_type: commentType}, function(response) {
			response = response.split("|");

			if ("success" == response[0]) {
				$("#comment_"+response[1]).fadeOut();
			} else if ("error" == response[0]) {
				alert('Błąd podczas usuwania komentarza!');
			} else if ("wrong_id" == response[0]) {
				alert("Nie ma takiego komentarza! Być może ktoś Cię uprzedził.");
			}
		});
	}

	return false;
};


function restore_hided_comment(commentId) {
	$.get("/admin/comment/restore_hided_comment/"+commentId, {}, function(response) {
		response = response.split("|");

		if ("success" == response[0]) {
			$("#comment_"+response[1]).fadeOut();
		} else if ("error" == response[0]) {
			alert('Błąd podczas przywracania komentarza!');
		} else if ("wrong_id" == response[0]) {
			alert("Nie ma takiego komentarza! Być może ktoś Cię uprzedził.");
		}
	});

	return false;
};


function change_auto_show_comments() {
	$.get("/comment/change_auto_show_comments", {}, function(response) {
		if ("disable" == response){
			//$("#comment_"+res[1]).fadeOut();
		} else if ("enable" == response) {
			//alert('włączone!');
		} else if ("disable" == response) {
			//alert("wyłączone!");
		} else if ("not_logged" == response) {
			//alert("Nie jesteś zalogowany.");
		}
	});

	return false;
};


function editComment(commentType, commentId, hasParent) {
	var $commentContent = $(".commcontent_"+commentId);

	$commentContent.html(
		'<textarea id="editedcomment">'+$commentContent.text()+'</textarea>'+
		'<br />'+
		'<input type="button" id="save_changes" value="Zapisz zmiany" onClick="commentEditSave(\''+commentType+'\', \''+commentId+'\'); return false" />'
	);
};


function commentEditSave(commentType, commentId) {
	var commentNewContent = $("#editedcomment").val();

	$.post("/comment/edit/"+commentId, {
		comment_type: commentType,
		text: commentNewContent
	}, function(response) {
		response = response.split('|');

		if ('ok' == response[0]) {
			$(".commcontent_"+commentId).text(commentNewContent);
		} else if ('badword' == response[0]) {
			var info = "Wykryto niedozwolone słowo w treści komentarza!";

			if (response[1]) {
				info += '<br />Lista wyrazów zakazanych: <br /><b class="red">'+response[1]+'</b>';
			}

			var $overlay = $("#overlay").fadeIn();
			var $modWin = $("#modWin").html(info).fadeIn();

			setTimeout(function() {
				$modWin.fadeOut();
				$overlay.fadeOut();
			}, 3000);
		} else {
			alert('Wystąpił błąd');
		}
	});

	return false;
}; // eo commentEditSave()


function comment_reply(commentType, commentedId, parentId) {
	if ('comment' != commentType && 'profile_comment' != commentType) {
		console.error('Nieprawidłowa wartość parametru comment_type');
	}

	var $replyForm = $("div.reply_form");
	if ($replyForm.is(':visible')) {
		$replyForm.remove();
	}

	$("#comment_"+parentId).after(
		'<div class="reply_form" style="display:none; padding-left:80px;">'+
			'<h3>Odpowiedz</h3>'+
			'<form name="comments">'+
				'<textarea name="comment" id="comment_reply" placeholder="Co o tym myślisz?"></textarea>'+
				'<br />'+
				'<input class="js-add_comment_button" data-comment-type="'+commentType+'" data-commented-id="'+commentedId+'" data-comment-parent-id="'+parentId+'" type="button" value="Dodaj komentarz" style="margin:2px" /> '+
				'<input class="commentclose" onClick="comment_close(); return false;" type="button" value="Anuluj" style="margin:2px" />'+
			'</form>'+
		'</div>'
	);

	$("div.reply_form").fadeIn();
};


/**
 * Zamyka okno odpowiedzi
 */
function comment_close() {
	var $replyForm = $("div.reply_form").fadeOut();

	setTimeout(function() {
		$replyForm.remove();
	}, 700);

	return false;
};

function getTarget() {
	var target = $.cookie('target');

	return (null == target) ? '' : target;
}


$(function() {

	/**
	 * Wyświetlanie „długich” demotów.
	 */
	(function() {
		var showLong = function(e) {
			e.preventDefault();

			var $button = $(this)
					.unbind('click', showLong)
					.removeClass('showlongbutton');

			var $pic = $button.parents('.pic');

			$pic.find('.hidelong').removeClass('hidelong');
			$pic.find('.hidelongarea').remove();
		};

		$('.showlongbutton').click(showLong);
	})();


	/**
	 * Ignorowanie wybranej osoby w komentarzach profilowych.
	 */
	var $container = $('.profile_comments_container');

	if ($container.length) {
		$('.ignore_user_button').live('click', function(e) {
			e.preventDefault();

			var username = $(this).attr('data-ignore_username');

			if (confirm('Czy na pewno chcesz dodać użytkownika „'+username+'” do ignorowanych?')) {
				$.ajax({
					type: 'POST',
					url: '/message/ignore/'+username,
					beforeSend: function() {
						__msg('Trwa ignorowanie użytkownika… <img src="/res/img/loading.gif" />', 0);
					},
					success: function(response) {
						var msg = '';

						switch (response) {
							case 'ok':
								msg = 'Użytkownik „'+username+'” od teraz będzie ignorowany.';

								// usuwam ze strony komentarze ignorowanego użytkownika
								$('.ignore_user_button[data-ignore_username="'+username+'"]')
									.parent('.comment')
									.fadeOut('slow')
									.remove();

								break;
							case 'is_admin':msg = 'Nie możesz dodać admina do ignorowanych!';break;
							case 'access_denied':msg = 'Nie masz uprawnień do skorzystania z tej akcji.';break;
							case 'selfignore':msg = 'Nie możesz ignorować samego siebie ;-)';break;
							case 'already_exists':msg = 'Już ignorujesz tego użytkownika.';break;
							case 'user_not_found':msg = 'Wybrany użytkownik nie istnieje.';break;
							default:msg = 'Wystąpił nieznany błąd, przepraszamy.';break;
						}
						__msg(msg, 4000);
					},
					error: function() {
						__msg('Wystąpił nieznany błąd, przepraszamy.', 4000);
					}
				}); // eo ajax()
			} // eo confirm()
		}); // eo live()
	}
});


if (logged_in) {
	$(function() {
		$('#hity_glowna').show();
	});
} else if (!logged_in && (glowna == 1)) {
	$(function() {
		$('#hity_glowna').show();
	});
}

$(function() {
	if(document.location.href.indexOf('/register') !== -1) {
		$('span.flogin').hide();
	}
	
	$('.facebook_login_button').bind('click', function() {
		FB.login(function(response) {
			if (response.authResponse) {
				document.location = "http://demotywatory.pl/faceconnect/connect";
			}
		});
	});
	
});


	if (null == $.cookie('online_user')) {
		$.get("http://demotywatory.pl/user/user_count");
	}


$(function() {
	// ładuję js tylko na stronie z dodawajką
	var $form = $("#adddemot form");
	if ($form.length > 0) {

		// kolor:
		(function() {
			$.fn.mColorPicker.init.allowTransparency = false;

			var section = $(".color_section", $form);

			var title = $("#title", $form);
			var color_label = $("#adddemot_color_label", section);
			var color_input = $("#adddemot_color", section);
			var color_preview = null;


			/**
			* Na starcie losuję kolor i nadaję go tytułowi i inputowi:
			*/
			(function() {
				var available_colors = [
					"#FFFFFF", "#C00000", "#FFFFFF", "#FCD000",
					"#FFFFFF", "#9acc00", "#FFFFFF", "#cc3dff",
					"#FFFFFF", "#ff142d", "#FFFFFF", "#ffe314",
					"#FFFFFF", "#1474ff", "#fe4dbc", "#FFFFFF",
					"#feb64d", "#FFFFFF"
				];
				var selected_color = available_colors[Math.floor(Math.random()*available_colors.length)];

				//jesli mamy kolor, to nie bierzemy wylosowanej wartosci
				var prechosen_color = color_input.attr('data-prechosen-color');

				if('undefined' != typeof prechosen_color){
					selected_color = prechosen_color;
				}
				
				color_input.val(selected_color);
				title.css("color", selected_color);

				color_input.mColorPicker();
				//color_preview = $("#adddemot .color_section #icp_adddemot_color");
				color_preview = $(".mColorPickerTrigger", section);
			})();

			// odpalam mColorPickera po kliknięciu na labela:
			color_label.click(function() {
				color_preview.trigger("click");
			});

			// aktualizuję kolor tytułu przy zmianie w mColorPickerze:
			color_input.live("change", function() {
				title.css("color", $(this).val());
			});
		})(); // eo kolor


		// ordinary:
		(function() {
			var $subtitleSection = $('input[name="text1"]', $form).parent();
			var $ordinary = $('input[name="is_ordinary"]', $form);

			var handleSubtitle = function() {
				if ($ordinary.is(':checked')) {
					$subtitleSection.slideUp();
				} else {
					$subtitleSection.slideDown();
				}
			};

			handleSubtitle();

			$ordinary.change(handleSubtitle);
		})(); // eo ordinary

	}
});


/**
 * POCZĄTEK OBSŁUGI OBRAZKA W DODAWAJCE
 *
 * Konwencja:
 *	* podkreślenia są używane do zmiennych przechowujących elementy DOM
 *	* camelStyle jest używany do zmiennych przechowujących dane
 */
$(function() {

	var inputType = 'local';
	var isInputValid = false;

	var $container = $('#adddemot');

	var $submit = $("#submit", $container);

	var $section = $(".file_original_section", $container);
	var $previewWrapper = $(".file_original_preview_wrapper", $section);
	var $inputType = $("input[name='file_original_input_type']", $section);

	var $sourceLabel = $('label[for="source"]', $container);


	/**
	 * Aktualizuje formularz w zależności od wprowadzanych danych źródłowego obrazka.
	 */
	function updateDom(callback) {
		callback = ("function" == typeof(callback)) ? callback : function(){};

		$(".input_type_button.active", $section).removeClass("active");
		$(".file_original_input", $section).removeAttr("disabled");


		// przełączamy się na upload z dysku:
		if ('local' == inputType) {
			$inputType.val('local');

			$sourceLabel.text('Źródło obrazka:');

			$(".file_original_input[type='url']", $section).attr("disabled", true);
			$(".input_type_button[value='local']", $section).addClass("active");

			if ('function' === typeof window.FileReader) {
				if (isInputValid) {
					$submit.removeAttr("disabled");
					$previewWrapper.show();
				} else {
					// jeśli obrazek się nie załaduje, to nie pozwalam na wysłanie formularza
					$submit.attr("disabled", "disabled");
					$previewWrapper.hide();
				}
			} else {
				$submit.removeAttr("disabled");
				$previewWrapper.hide();
			}

		// przełączamy się na upload z linka:
		} else if ('url' == inputType) {
			$inputType.val('url');

			$sourceLabel.text('Źródło obrazka:');

			$(".input_type_button[value='url']", $section).addClass("active");
			$(".file_original_input[type='url']", $section).attr("placeholder", "http://demotywatory.pl/obrazek.jpg");
			$(".file_original_input[type='file']", $section).attr("disabled", true);

			if (isInputValid) {
				$submit.removeAttr("disabled");
				$previewWrapper.show();
			} else {
				// jeśli obrazek się nie załaduje, to nie pozwalam na wysłanie formularza
				$submit.attr("disabled", "disabled");
				$previewWrapper.hide();
			}

		// przełączamy się na upload z YouTube:
		} else if ('youtube' == inputType) {
			$inputType.val('url');

			$sourceLabel.text('Źródło filmu:');

			$(".input_type_button[value='youtube']", $section).addClass("active");
			$(".file_original_input[type='url']", $section).attr("placeholder", "http://www.youtube.com/watch?v=v1PBptSDIh8")
			$(".file_original_input[type='file']", $section).attr("disabled", true);

			if (isInputValid) {
				$submit.removeAttr("disabled");
				$previewWrapper.show();
			} else {
				// jeśli obrazek się nie załaduje, to nie pozwalam na wysłanie formularza
				$submit.attr("disabled", "disabled");
				$previewWrapper.hide();
			}
		}

		callback();
	} // eo updateDom()


	/**
	 * Odświeża podgląd podane linka (do obrazka lub youtube).
	 */
	var refreshInput = function() {
		$previewWrapper.html("&nbsp;");
		isInputValid = false;

		var callback = function() {
			if ("undefined" !== typeof(urlParams['instant']) && !MSI.picAddForm.hasErrors) {
				$container.find('input[name="priv"]').attr('checked', 'checked');
				$submit.show().click();
			}
		};

		var url = $(".file_original_input[type='url']").val();

		if ('url' == inputType && '' != url) {

			var preview_image = $('<img alt="" src="' + url + '" />');
			preview_image.attr(
				"src",
				url
			).load(function() {
				$previewWrapper.html(preview_image);
				isInputValid = true;
				updateDom(callback);
			}).error(function() {
				updateDom();
			});

		} else if ('youtube' == inputType) {
			var youtube_id = false;
			if(url.match('http://(www.)?youtube|youtu\.be')){
				 youtube_id=url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
			}
			if (youtube_id) {
				$previewWrapper.html(
					'<iframe width="160" src="http://www.youtube.com/embed/'
					+ youtube_id +
					'?rel=0&autohide=1&showinfo=0&fs=1&egm=0" frameborder="0" allowfullscreen=""></iframe>'
				);
				isInputValid = true;
			}
			updateDom(callback);

		} else {
			var $fileInput = $('.file_original_input[type="file"]');

			if ('local' == inputType && 'function' === typeof window.FileReader && "" != $fileInput.val()) {
				var file = $fileInput[0].files[0];
				var fileReader = new FileReader();

				fileReader.onload = function(e) {
					var img = new Image();
					img.src = e.target.result;
					$previewWrapper.html($(img));
					isInputValid = true;
					updateDom();
				};

				fileReader.readAsDataURL(file);
			} else {
				updateDom();
			}
		}
	};


	/**
	 * Ładuję od razu zakładkę z URLem, jeśli jest podany w parametrach.
	 */
	(function() {
		if ("undefined" !== typeof(urlParams["url"])) {
			inputType = 'url';

			setTimeout(function() {
				$section.find(".input_type_button[value='url']").trigger("click");
			}, 0);

			$section.find(".file_original_input[type='url']").val(urlParams['url']);

			$section.find(".file_original_preview").attr("src", urlParams['url']);
		}
	})();


	/**
	 * Zmiana sposobu wrzucania obrazka: z dysku lub URLa.
	 */
	$(".input_type_button", $section).click(function(e) {
		e.preventDefault();
		inputType = $(this).val();
		refreshInput();
	});

	/**
	 * Ładowanie podglądu obrazka wpisanego w URLu.
	 */
	$(".file_original_input[type='url']", $section).keyup(refreshInput);

	$('.file_original_input[type="file"]', $section).change(refreshInput);
});
/**
 * KONIEC OBSŁUGI OBRAZKA W DODAWAJCE
 */


/**
 * jQuery.tagSuggest() 1.4
 *
 * Przerobione i dostosowane do dodawajki demotów @by MacDada.
 * Może komuś będzie chciało się to uogólnić? ;-]
 *
  @author: remy sharp / http://remysharp.com
  @url: http://remysharp.com/2007/12/28/jquery-tag-suggestion/
  @usage: setGlobalTags(['javascript', 'jquery', 'java', 'json']); // applied tags to be used for all implementations
          $('input.tags').tagSuggest(options);

          The selector is the element that the user enters their tag list
  @params:
    matchClass - class applied to the suggestions, defaults to 'tagMatches'
    tagContainer - the type of element uses to contain the suggestions, defaults to 'span'
    tagWrap - the type of element the suggestions a wrapped in, defaults to 'span'
    sort - boolean to force the sorted order of suggestions, defaults to false
    url - optional url to get suggestions if setGlobalTags isn't used.  Must return array of suggested tags
    tags - optional array of tags specific to this instance of element matches
    delay - optional sets the delay between keyup and the request - can help throttle ajax requests, defaults to zero delay
    separator - optional separator string, defaults to ' ' (Brian J. Cardiff)
  @license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
  @version: 1.4
  @changes: fixed filtering to ajax hits
*/
(function($) {
    var globalTags = [];

    // creates a public function within our private code.
    // tags can either be an array of strings OR
    // array of objects containing a 'tag' attribute
    window.setGlobalTags = function(tags /* array */) {
        globalTags = getTags(tags);
    };

    function getTags(tags) {
        var tag, i, goodTags = [];
        for (i = 0; i < tags.length; i++) {
            tag = tags[i];
            if (typeof tags[i] == 'object') {
                tag = tags[i].tag;
            }
            goodTags.push(tag.toLowerCase());
        }

        return goodTags;
    }

    $.fn.tagSuggest = function (options) {
        var defaults = {
            'matchClass' : 'tagMatches',
            'tagContainer' : 'span',
            'tagWrap' : 'span',
            'sort' : true,
            'tags' : null,
            'url' : null,
            'delay' : 0,
            'separator' : ' ',
			'tagsAlwaysVisible' : false,
			'maxTagsCount' : false,
			'max_tags_count_alert_box' : false
        };

        var i, tag, userTags = [], settings = $.extend({}, defaults, options);

        if (settings.tags) {
            userTags = getTags(settings.tags);
        } else {
            userTags = globalTags;
        }


        return this.each(function () {
            var tagsElm = $(this);
            var elm = this;
            var matches, fromTab = false;
            var suggestionsShow = false;
            var workingTags = [];
            var currentTag = {"position": 0, tag: ""};
            var tagMatches = document.createElement(settings.tagContainer);

            function showSuggestionsDelayed(el, key) {
                if (settings.delay) {
                    if (elm.timer) clearTimeout(elm.timer);
                    elm.timer = setTimeout(function () {
                        showSuggestions(el, key);
                    }, settings.delay);
                } else {
                    showSuggestions(el, key);
                }
            }

            function showSuggestions(el, key) {
                workingTags = el.value.split(settings.separator);
                matches = [];
                var i, html = '', chosenTags = {}, tagSelected = false;

                // we're looking to complete the tag on currentTag.position (to start with)
                currentTag = {position: currentTags.length-1, tag: ''};

                for (i = 0; i < currentTags.length && i < workingTags.length; i++) {
                    if (!tagSelected &&
                        currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                        currentTag = {position: i, tag: workingTags[i].toLowerCase()};
                        tagSelected = true;
                    }
                    // lookup for filtering out chosen tags
                    chosenTags[currentTags[i].toLowerCase()] = true;
                }

                if (currentTag.tag) {
                    // collect potential tags
                    if (settings.url) {
                        $.ajax({
                            'url' : settings.url,
                            'dataType' : 'json',
                            'data' : {'tag' : currentTag.tag},
                            'async' : false, // wait until this is ajax hit is complete before continue
                            'success' : function (m) {
                                matches = m;
                            }
                        });
                    } else {
						userTags = getTags(settings.tags);

                        for (i = 0; i < userTags.length; i++) {
                            if (userTags[i].indexOf(currentTag.tag) === 0) {
                                matches.push(userTags[i]);
                            }
                        }
                    }

                    matches = $.grep(matches, function (v, i) {
                        return !chosenTags[v.toLowerCase()];
                    });

                    if (settings.sort) {
                        matches = matches.sort();
                    }

                    for (i = 0; i < matches.length; i++) {
                        html += '<' + settings.tagWrap + ' class="_tag_suggestion">' + matches[i] + '</' + settings.tagWrap + '>';
                    }

                    tagMatches.html(html);
					alertOnMaxTagsCount();
                    suggestionsShow = !!(matches.length);
                } else {
                    hideSuggestions();
                }
            }

            function hideSuggestions() {
				/**
				 * Tagi widoczne nawet kiedy nie są wpisywane.
				 * @by MacDada
				 */
				if (settings.tagsAlwaysVisible) {

					var html = "";
					var tagsToShow = getTags(settings.tags);
					workingTags = $("#tags")[0].value.split(settings.separator);

					// usuwam z listy tagi, które już są wybrane:
					for (var i in tagsToShow) {
						for (var j in workingTags) {
							if (workingTags[j] == tagsToShow[i]) {
								tagsToShow.splice(i, 1);
							}
						}
					}

					if (settings.sort) {
						tagsToShow = tagsToShow.sort();
					}

					for (i = 0; i < tagsToShow.length; i++) {
						html += '<' + settings.tagWrap + ' class="_tag_suggestion">' + tagsToShow[i] + '</' + settings.tagWrap + '>';
					}

					tagMatches.html(html);
					alertOnMaxTagsCount();

				} else {
					tagMatches.empty();
				}

                matches = [];
                suggestionsShow = false;
            }


			function alertOnMaxTagsCount() {
				if (settings.maxTagsCount) {
					var category_tags_count = 0;
					var tagsToShow = getTags(settings.tags);
					workingTags = $("#adddemot form #tags")[0].value.split(settings.separator);

					for (var i in tagsToShow) {
						for (var j in workingTags) {
							if (workingTags[j] == tagsToShow[i]) {
								category_tags_count++;
								if (category_tags_count > 3) {
									break;
								}
							}
						}
						if (category_tags_count > 3) {
							break;
						}
					}

					if (category_tags_count > 3) {

						if (!settings.max_tags_alert_box) {
							settings.max_tags_alert_box = $(
								'<div class="max_tags_count_alert">'+
									'Pamiętaj, że tylko 3 tagi kategorii będą brane pod uwagę.'+
								'</div>'
							).insertAfter("#adddemot form .tagMatches").slideDown("slow");
						} else {
							settings.max_tags_alert_box.slideDown("slow");
						}

					} else if (settings.max_tags_alert_box) {
						settings.max_tags_alert_box.slideUp();
					}
				}
			}


            function setSelection() {
                var v = tagsElm.val();

                // tweak for hintted elements
                // http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
                if (v == tagsElm.attr('title') && tagsElm.is('.hint')) {
					v = '';
				}

                currentTags = v.split(settings.separator);
                hideSuggestions();
            }

            function chooseTag(tag) {
                var i, index;
                for (i = 0; i < currentTags.length; i++) {
                    if (currentTags[i].toLowerCase() != workingTags[i].toLowerCase()) {
                        index = i;
                        break;
                    }
                }

                if (index == workingTags.length - 1) tag = tag + settings.separator;

                workingTags[i] = tag;

                tagsElm.val(workingTags.join(settings.separator));
                tagsElm.blur().focus();
                setSelection();
            }

            function handleKeys(ev) {
                fromTab = false;
                var type = ev.type;
                var resetSelection = false;

                switch (ev.keyCode) {
                    case 37: // ignore cases (arrow keys)
                    case 38:
                    case 39:
                    case 40: {
                        hideSuggestions();
                        return true;
                    }
                    case 224:
                    case 17:
                    case 16:
                    case 18: {
                        return true;
                    }

                    case 8: {
                        // delete - hide selections if we're empty
                        if (this.value == '') {
                            hideSuggestions();
                            setSelection();
                            return true;
                        } else {
                            type = 'keyup'; // allow drop through
                            resetSelection = true;
                            showSuggestionsDelayed(this);
                        }
                        break;
                    }

                    case 9: // return and tab
                    case 13: {
                        if (suggestionsShow) {
                            // complete
                            chooseTag(matches[0]);

                            fromTab = true;
                            return false;
                        } else {
                            return true;
                        }
                    }
                    case 27: {
                        hideSuggestions();
                        setSelection();
                        return true;
                    }
                    case 32: {
                        setSelection();
                        return true;
                    }
                }

                if (type == 'keyup') {
                    switch (ev.charCode) {
                        case 9:
                        case 13: {
                            return true;
                        }
                    }

                    if (resetSelection) {
                        setSelection();
                    }
                    showSuggestionsDelayed(this, ev.charCode);
                }
            }

            tagsElm.after(tagMatches).keypress(handleKeys).keyup(handleKeys).blur(function () {
                if (fromTab == true || suggestionsShow) { // tweak to support tab selection for Opera & IE
                    fromTab = false;
                    tagsElm.focus();
                }
            });

            // replace with jQuery version
            tagMatches = $(tagMatches).click(function (ev) {
                if (ev.target.nodeName == settings.tagWrap.toUpperCase() && $(ev.target).is('._tag_suggestion')) {
                    chooseTag(ev.target.innerHTML);
                }
            }).addClass(settings.matchClass);

            // initialise
            setSelection();
        });
    };
})(jQuery);

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('l(2M 2==\'2L\'){4 2={}}2.c=\'/1h/n/25/\';2.G=\'2N://2O.2Q/5/2P\';2.g=6(){4 $B=$(\'.U.D\');4 $Y=$(\'.U.r\');4 $7=$(\'#C\');4 $1M=$(\'.2f\');4 $1N=$(\'.29\');4 $2k=$(\'.1R\');4 $2p=$("[h^=2K]");4 1K=\'<!-- 2J -->\';6 H(1E){l(1E.o>0){1E.k(1K)}};H($1M);H($1N);H($2k);H($7);H($Y);H($B);H($2p)};2.1s=6(){4 8=2.c+\'2E.n\';4 $7=$(\'#C\');l($7.o>0){$7.k(\'<3 h="b"></3>\');2.m(8,N,W,\'b\')}};2.1q=6(){4 8=2.c+\'2D.n\';4 $7=$(\'#C\');l($7.o>0){$7.k(\'<3 h="b"></3>\');2.m(8,N,1P,\'b\')}};2.V=6(){4 8=2.c+\'2C.n\';4 $7=$(\'#C\');l($7.o>0){$7.k(\'<3 h="b"></3>\');2.m(8,N,2F,\'b\')}};2.1r=6(){4 8=2.c+\'2G.n\';4 $1j=$(\'.2f\');4 $1k=$(\'.29\');4 $1l=$(\'.1R\');l($1j.o>0){$1j.k(\'<3 h="b"></3>\');2.m(8,W,1i,\'b\')}l($1k.o>0){$1k.k(\'<3 h="2a"></3>\');2.m(8,W,1i,\'2a\')}l($1l.o>0){$1l.k(\'<3 h="2d"></3>\');2.m(8,W,1i,\'2d\')}};2.1x=6(){4 9=2.c+\'2I.Z\';4 $7=$(\'#C\');4 $9=$(\'<3 h="b"><a S="\'+2.G+\'"><M Q="\'+9+\'" /></a><3 u="A"></3></3>\');4 $A=$(\'.A\',$9);l($7.o>0){$7.d({p:\'19\',t:\'18\',v:\'0 O\'});$9.d({f:\'16\',\'z-E\':\'1W\'});$A.d({t:\'2H\',p:\'1o\',w:"13(\'"+2.c+"2R.K\')",f:\'s\',D:\'1y\',q:\'1y\',P:\'L\'});$A.X(6(){$9.d(\'f\',\'2S\');$A.34()});$7.k($9)}};2.1v=6(){4 8=2.c+\'33.n\';4 $7=$(\'#C\');l($7.o>0){$7.k(\'<3 h="b"></3>\');$(\'1a\').d({\'w-f\':\'35 36\',\'w-2h\':\'38-2h\',\'w-37\':\'13(/1h/n/25/2B.Z)\',P:\'L\'}).X(6(){1Q.1I.S=2.G});2.m(8,N,1P,\'b\')}};2.1u=6(){4 8=2.c+\'31.n\';4 $Y=$(\'.U.r\');4 $B=$(\'.U.D\');l($B.o>0){$B.k(\'<3 h="b"></3>\');2.m(8,1Y,1b,\'b\')}2V l($Y.o>0){$Y.k(\'<3 h="b"></3>\');2.m(8,1Y,1b,\'b\')}};2.1m=6(){4 8=2.c+\'2U.n\';4 $B=$(\'.U.D\');l($B.o>0){$B.k(\'<3 h="b"></3>\');2.m(8,2T,1b,\'b\')}};2.1t=6(){4 8=2.c+\'1S.n\';4 $7=$(\'#C\');l($7.o>0){$7.d({f:\'17\',p:\'19\',t:\'18\',v:\'0 O\',\'z-E\':\'1d\'});$7.k(\'<3 R="f: s;"><3 h="b"></3></3>\');2.m(8,N,W,\'b\')}};2.1G=6(){4 8=2.c+\'2W.n\';4 $7=$(\'#C\');l($7.o>0){$7.d({f:\'17\',p:\'2X\',t:\'18\',v:\'0 O\',\'z-E\':\'1d\'});$7.k(\'<3 R="f: s;"><3 h="b"></3></3>\');2.m(8,N,2Z,\'b\')}};2.1p=6(){4 8=2.c+\'2Y.n\';4 $1f=$(\'<3 u="1V"><3 u="39"><3 h="b"></3></3></3>\');4 $14=$(\'.1V\',$1f);$1f.d({f:\'16\',2q:\'1y\',r:\'1z%\',\'v-r\':\'-2s\'});$14.d({t:\'2r\',p:\'2A\',v:\'0 O\'});$(\'#2y\').2z($1f);2.m(8,2x,30,\'b\')};2.1n=6(){4 $F=$(\'#F\');4 $J=$(\'#J\');4 $9=$(\'<3 u="2t"><a S="\'+2.G+\'"><M Q="\'+2.c+\'2w.Z" /></a></3>\');4 $I=$(\'<3 u="I"></3>\');$F.d({1X:\'22\',\'21\':\'1\',\'w-15\':\'1Z\'});$J.d({\'w-15\':\'1B\',2o:\'2n\',2b:\'0\',q:\'O\',\'v-r\':\'-2u\'}).k($9).2e();$I.d({f:\'s\',q:\'1T\',D:\'1T\',P:\'L\',t:\'2v\',p:\'23\',\'w\':"13(\'"+2.c+"32.K\')"}).X(6(){2g()});$F.11($I)};2.1H=6(){4 $F=$(\'#F\');4 $J=$(\'#J\');4 $9=$(\'<3 u="3R"><a S="\'+2.G+\'"><M Q="\'+2.c+\'3Q.Z" /></a></3>\');4 $I=$(\'<3 u="I"></3>\');$F.d({1X:\'22\',\'21\':\'1\',\'w-15\':\'1Z\',q:\'-2c\'});$J.d({\'w-15\':\'1B\',2o:\'2n\',2b:\'0\',q:\'-2c\',\'v-r\':\'-3P\'}).k($9).2e();$I.d({f:\'s\',q:\'3S\',r:\'3T\',P:\'L\',t:\'3V\',p:\'1U\',\'w\':"13(\'"+2.c+"3U.K\')"}).X(6(){2g()});$J.11($I);3O(6(){$F.1w({q:\'0\'},1O,6(){$J.d(\'q\',\'O\')})},1O)};2.1F=6(){4 8=2.c+\'3N.n\';4 $B=$(\'.U.D\');l($B.o>0){$B.k(\'<3 R="f: 17; p:3a; t:3H; z-E:1d;"><3 R="f: s; r: -3G;"><3 h="b"></3></3></3>\');2.m(8,3J,1b,\'b\')}};2.1D=6(){4 8=2.c+\'3K.n\';4 $9=$(\'<3 u="26"><3 h="b"></3></3>\');4 $14=$(\'.26\',$9);$(\'1a\').11($9);$9.d({f:\'s\',q:\'3X\',D:\'0\',P:\'L\',t:\'1e\',p:\'1e\',\'z-E\':\'3L\'});2.m(8,1e,1e,\'b\')};2.1c=6(){4 9=2.c+\'28.K\';4 $T=$(\'<3 h="28"></3>\');$(\'1a\').3W($T);4 $9=$(\'<3 h="44"><a S="\'+2.G+\'"><M Q="\'+9+\'" /></a><3 u="A"></3></3>\');4 $A=$(\'.A\',$9);l($T.o>0){$T.d({f:\'s\'});$9.d({f:\'16\',r:\'1z%\',q:\'46\',\'v-r\':\'-43\',\'z-E\':\'1W\'});$A.d({t:\'42\',p:\'1U\',w:"13(\'"+2.c+"3Z.K\')",f:\'s\',D:\'1o\',q:\'1o\',P:\'L\'});$A.X(6(){$T.2i()});$T.k($9)}};2.1A=6(){4 8=2.c+\'1S.n\';4 $7=$(\'#C\');$7.41(6(){$7.1L().1w({p:\'1g\'})},6(){$7.1L().1w({p:\'19\'})});l($7.o>0){$7.d({f:\'17\',p:\'19\',t:\'18\',v:\'0 O\',\'z-E\':\'1d\',47:\'45\'});$7.k(\'<3 R="f: s;"><3 h="b"></3></3>\');2.m(8,N,W,\'b\')}};2.24=6(){4 9=2.c+\'3k.Z\';4 $9=$(\'<3 h="3j"><M Q="\'+2.c+\'3l.K" u="27" /><a S="\'+2.G+\'" 3m="3o"><M Q="\'+9+\'"></a></3>\');$9.d({t:\'1g\',p:\'1g\',f:\'16\',\'z-E\':\'3i\',r:\'1z%\',\'v-r\':\'-3h\',\'v-q\':\'-3c\'});$(\'#C\').11($9);4 $1C=$(\'.27\',$9);$1C.d({q:\'3b\',D:\'0\',P:\'L\',f:\'s\'});$1C.X(6(){$9.2i()})};2.2m=6(){4 9=2.c+\'3e.K\';$(\'1a\').11(\'<M u="1J" R="f: s; z-E: 3z;" Q="\'+9+\'" />\');$(3C).3D(6(e){$(\'.1J\').3y({r:e.3s,q:e.3t+20})})};2.m=6(8,x,y,14){4 2j={3w:"3v",3I:"3u",3r:"3x",3B:"3A",3q:\'1B\'};4 2l={3p:2.G};3f.3g(8,14,x,y,"10.0.12","/1h/n/3F.n",2l,2j)};$(6(){3M(1Q.1I.40){i\'?1s\':2.g();2.1s();j;i\'?1q\':2.g();2.1q();j;i\'?V\':2.g();2.V();j;i\'?1r\':2.g();2.1r();j;i\'?1x\':2.g();2.1x();j;i\'?1v\':2.g();2.1v();j;i\'?1u\':2.g();2.1u();j;i\'?1m\':2.g();2.1m();j;i\'?1t\':2.g();2.1t();j;i\'?1G\':2.g();2.1G();j;i\'?1p\':2.g();2.1p();j;i\'?1n\':2.g();2.1n();j;i\'?1H\':2.g();2.1H();j;i\'?1F\':2.g();2.1F();j;i\'?1D\':2.g();2.1D();j;i\'?1c\':2.g();2.1c();j;i\'?1A\':2.g();2.1A();j;i\'?3d\':2.g();2.V();2.1c();j;i\'?3n\':2.g();2.2m();2.V();j;i\'?3E\':2.g();2.V();2.24();3Y:j}});',62,256,'||MSI|div|var||function|bill|adSwf|ad||monsterFlash|MonsterSource|css||position|MonsterClearPage|id|case|break|html|if|embedMonster|swf|length|height|top|left|absolute|width|class|margin|background||||closeMonster|sky_right|adad|right|index|overlay|MonsterExampleUrl|clearMonster|monsterClose|modWin|png|pointer|img|750|auto|cursor|src|style|href|layer|sky|MonsterBillboard|300|click|sky_left|jpg||append||url|container|color|fixed|relative|750px|100px|body|600|MonsterTopLayer|101|500|scroller|300px|res|250|rectangle|rectangle2|rectangle3|MonsterSkyscrapper120x600|MonsterIntromercial|20px|MonsterScroller|MonsterDoubleBillboard|MonsterRectangle|MonsterTripleBillboard|MonsterExpandBillboard|MonsterSkyscrapper160x600|MonsterScreeningDoubleBillboard|animate|MonsterScrollBillboard|0px|50|MonsterPushBillboard|transparent|close|MonsterCorner|obj|MonsterExpandSkyscrapper|MonsterExpandDoubleBillboard|MonsterIterstitial|location|monsterFly|clear_msg|stop|rect1|rect2|3000|200|window|box_336_3|expand_billboard_750x100|40px|23px|monsterScrollerContainer|111|display|160|white||opacity|block||MonsterBrandmark|monster|monsterFlashContainer|closeMonsterBrand|toplayer|box_336_2|monsterFlash2|padding|9999px|monsterFlash3|show|box_336_1|waitDialogToggle|repeat|remove|params|rect3|flashvars|MonsterCursor|none|border|adsense|bottom|1300px|650px|monsterIntromercial|450px|156|intromercial|1300|footer|after|30px|screening_tapeta|billboard_750x100|doublebillboard_750x200|triplebillboard_750x300|100|rectangle_300x250|75px|scrollbillboard|MonsterClear|afbd_|undefined|typeof|http|mmg|produkty_reklamowe|pl|scrollbillboard_zamknij|static|120|skyscrapper_120x600|else|expand_doublebillboard_750x200|200px|scroller_1300x30|400||skyscrapper_160x600|intromercial_przejdz_do_serwisu|screening_doublebillboard_750x200|fadeOut|center|141px|image|no|monsterScroller|600px|1px|160px|MonsterBillboardAndTopLayer|comet_cursor_50x50|swfobject|embedSWF|150px|999|monsterBrand|brandmark|brandmark_zamknij|target|MonsterBillboardAndCursor|_blank|clickTag|wmode|allowFullscreen|pageX|pageY|showall|high|quality|false|offset|9999|always|allowScriptAccess|document|mousemove|MonsterBillboardAndBrandmark|expressInstall|330px|120px|scale|450|corner|80|switch|expand_skyscrapper_120x600|setTimeout|320px|iterstitial|monsterIterstitial|55px|550px|iterstitial_zamknij|83px|prepend|24px|default|toplayer_zamknij|search|hover|82px|298px|monsterFlashTopLayer|hidden|50px|overflow'.split('|'),0,{}));

	if (!MSI){
		var MSI = {};
	}
	MSI.turn_off_activities = function(){
		$('.social_reader .fb_friends').before($('<div id="fb_friends_overlay" />').hide().fadeIn().text('Aby zobaczyć aktywność swoich znajomych, włącz aktywności'));
		$('.fb_friend').css('opacity', '0.3');
	}
	MSI.turn_on_activities = function(){
		$('.social_reader .fb_friend').animate({opacity: 1});
		$('#fb_friends_overlay').fadeOut(function(){
			$(this).remove();
		});
	}
	
	MSI.hide_social_reader = function(self, saveToCookie){
		if (undefined == saveToCookie) { saveToCookie = true; }
		var social_reader = $('.social_reader');
		
		self.addClass('scrolled');
		self.removeClass('notscrolled');
		social_reader.css('overflow', 'hidden');
		social_reader.animate({height: '31px'});
		
		$('#friends_paginator').fadeOut();
		if (saveToCookie) {
			$.cookie("hide_social_reader", true, { path: '/' });
		}
	}
	
	MSI.show_social_reader = function(self){
		var social_reader = $('.social_reader');

		self.removeClass('scrolled');
		self.addClass('notscrolled');
		social_reader.animate({height: '116'});
		
		$.cookie("hide_social_reader", null, { path: '/' });
		$('#friends_paginator').fadeIn(function(){
			social_reader.css('overflow', 'visible');
		});
	}
	
	MSI.share_add = function(demot_id){
		$.ajax({
			url: "/facebook/share_add/"+demot_id,
			type: 'GET'
//			success: function(data) {
//				var data = JSON.parse(data);
//			},
//			error: function(obj) {
//				//errorFunctions(obj);
//			}
		});
	}
	
	MSI.share_delete = function(share_id, obj){
		$.ajax({
			url: "/facebook/share_delete/"+share_id,
			type: 'GET'
//			success: function(data) {
//				var data = JSON.parse(data);
//				if(data.success){
////					obj.parents('.fb_feed').fadeOut().remove();
//				}
//			}
		});
	}
	
	MSI.get_my_feeds = function(){
		FB.api('/me/news.reads', function(response) {
			var feed_container = $('.social_reader .fb_account .fb_my_feeds');

			if(response.data.length == 0){
				feed_container.append('<div class="fb_feed"><h3>Brak dotychczasowych aktywności</h3></div>');
			}else{
				feed_container.addClass('feeds_loaded');
			}
			
			var feeds = $.tmpl($.base64Decode('e3tlYWNoKGksIGRhdGEyKSBkYXRhfX0KCTxkaXYgY2xhc3M9ImZiX2ZlZWQgZGF0YSI+CgkJPGRpdiBjbGFzcz0ic291cmNlIj4KCQkJPGEgaHJlZj0iJHtkYXRhMi5kYXRhLmFydGljbGUudXJsfSIgdGFyZ2V0PSJfYmxhbmsiPiR7ZGF0YTIuZGF0YS5hcnRpY2xlLnRpdGxlfTwvYT4KCQk8L2Rpdj4KCQk8ZGl2IGNsYXNzPSJkZWxldGUiIGRhdGEtYWN0aW9uX2lkPSIke2RhdGEyLmlkfSI+PC9kaXY+Cgk8L2Rpdj4Ke3svZWFjaH19CjxkaXYgaWQ9Im15X2ZlZWRzX3BhZ2luYXRvciI+PC9kaXY+'), {
				data: response.data
			});
			
			feed_container.append(feeds);
			
			$('#my_feeds_paginator').smartpaginator({ totalrecords: (response.data.length > 20) ? 20 : response.data.length,
				recordsperpage: 5,
				datacontainer: 'fb_my_feeds', 
				dataelement: 'div.fb_feed',
				next: '',
				prev: '',
				onlyprevnext: true,
				theme: 'black' });

		});
	}
	
	MSI.feeds_paginator = function(){
		var feeds = $('.social_reader .fb_friends_feeds_container');
		$.each(feeds, function(index, feeds_container) {
			var container_id = $(feeds_container).attr('id');
			var feeds_count = $('.fb_feed', $(feeds_container)).length;

			if(feeds_count > 5){
				$('#' + container_id + '_feeds').append('<div class="friends_feeds_paginator" />');
				$('.friends_feeds_paginator', $('#'+container_id)).smartpaginator({ totalrecords: feeds_count,
					recordsperpage: 5,
					datacontainer: container_id + '_feeds', 
					dataelement: 'div.fb_feed',
					next: '',
					prev: '',
					onlyprevnext: true,
					theme: 'black' 
				});
			}
		});
	}
	
	MSI.friends_per_page = 9;
	MSI.friends_paginator = function(){
		$('#friends_paginator').smartpaginator({ totalrecords: $('.social_reader .fb_friend').length,
			recordsperpage: MSI.friends_per_page,
			datacontainer: 'fb_friends', 
			dataelement: 'div.fb_friend',
			next: '',
			prev: '',
//			controlsalways: true,
			onlyprevnext: true,
			theme: 'black' });
	}
	
	 $('.social_reader div.delete').live('click', function(e){
		var self = $(this);
		self.parents('.fb_feed').css("opacity", '0.3');
		var share_id = self.attr('data-action_id');

		MSI.share_delete(share_id, self);
		self.css('color', 'red');

		e.preventDefault();
	 });

	MSI.get_friends = function(){
		
		var friendsInstalled = [];
		var queries = [];
		var people_max_count = 50;
		var friends_div = $('.social_reader .fb_friends');
		
		FB.api("/me/friends?fields=installed,name", function(response){
			var friends = response.data;
			var ic=1;
			for(var i in friends){
				if(friends[i].installed){
					var friend = friends[i];
					if(friendsInstalled.length < people_max_count){
						
						var new_friend = $.tmpl($.base64Decode('PGRpdiBjbGFzcz0iZmJfZnJpZW5kX2NvbnRhaW5lciBmYl8ke2ZyaWVuZC5pZH0iPgoJPGRpdiBjbGFzcz0iZmJfZnJpZW5kIj4KCQk8aW1nIHNyYz0iaHR0cDovL2dyYXBoLmZhY2Vib29rLmNvbS8ke2ZyaWVuZC5pZH0vcGljdHVyZT90eXBlPXNxdWFyZSIgYWx0PSIke2ZyaWVuZC5uYW1lfSIgLz4KCQk8ZGl2IGlkPSJmYl8ke2ZyaWVuZC5pZH0iIGNsYXNzPSJmYl9mcmllbmRzX2ZlZWRzX2NvbnRhaW5lciI+CgkJCTxkaXYgY2xhc3M9ImZiX2NvdmVyZXIiPjwvZGl2PgoJCQk8ZGl2IGlkPSJmYl8ke2ZyaWVuZC5pZH1fZmVlZHMiIGNsYXNzPSJmYl9mcmllbmRzX2ZlZWRzIj4KCQkJCTxoMT4ke2ZyaWVuZC5uYW1lfTwvaDE+CgkJCQk8ZGl2IGNsYXNzPSJub19mZWVkcyI+QnJhayBha3R5d25vxZtjaTwvZGl2PgoJCQk8L2Rpdj4KCQk8L2Rpdj4KCTwvZGl2Pgo8L2Rpdj4='), {
							friend: friend
						});
	
						queries.push({"method": "GET", "relative_url": "/" + friend.id + "/news.reads?date_format=d-m-Y%20H:i&limit=60"});
						friendsInstalled.push(friend);
						friends_div.append(new_friend.hide().fadeIn(1000));
						
						
												if(ic % (MSI.friends_per_page - 1) == 0 && ic !=0 ){
							var fake = $.tmpl($.base64Decode('PGRpdiBjbGFzcz0iZmJfZnJpZW5kX2NvbnRhaW5lciI+Cgk8ZGl2IGNsYXNzPSJmYl9mcmllbmQgaW52aXRlIj4KCQk8aW1nIHNyYz0iL3Jlcy9pbWcvc29jaWFsX3JlYWRlci96YXByb3Nfem5ham9tZWdvLnBuZyIgYWx0PSJaYXByb8WbIHpuYWpvbXljaCEiIC8+Cgk8L2Rpdj4KPC9kaXY+'));
							friends_div.append(fake.hide().fadeIn(1000));
						}
						ic++;
					}
				}
			}

						if((ic-1) % (MSI.friends_per_page - 1) != 0){
				var fake = $.tmpl($.base64Decode('PGRpdiBjbGFzcz0iZmJfZnJpZW5kX2NvbnRhaW5lciI+Cgk8ZGl2IGNsYXNzPSJmYl9mcmllbmQgaW52aXRlIj4KCQk8aW1nIHNyYz0iL3Jlcy9pbWcvc29jaWFsX3JlYWRlci96YXByb3Nfem5ham9tZWdvLnBuZyIgYWx0PSJaYXByb8WbIHpuYWpvbXljaCEiIC8+Cgk8L2Rpdj4KPC9kaXY+'));
				friends_div.append(fake.hide().fadeIn(1000));
			}
			
			if(!user_facebook_shares){
				MSI.turn_off_activities();
			}
			
			FB.api("/", "POST", {
				batch: queries
			}, function(share_responses) {
				
				for(var i_r in share_responses){
					var response = JSON.parse(share_responses[i_r].body);
					if(response.data){

						if(response.data.length > 0){
							for(var i_d in response.data){
								var share = response.data[i_d].data.article;
								var from = response.data[i_d].from.id;
								var ff = $('.fb_friends #fb_'+from);
								var friends_feeds = $('.fb_friends_feeds', ff);
								friends_feeds.append('<div class="fb_feed"><a href="'+share.url+'" target="_blank">'+share.title+'</a></div>');
							}
							ff.addClass('feeds_loaded');
							if($('.no_feeds', ff).length > 0){
								$('.no_feeds', ff).remove();
							}
						}
					}
				}
								MSI.feeds_paginator();
			});
			
			MSI.friends_paginator();
		});
		
//		$('#black').smartpaginator({ totalrecords: fiCount,
//			recordsperpage: 9,
//			datacontainer: 'fb_friends', 
//			dataelement: 'div',
//			theme: 'black' 
//		});
	}
	 
	 
	$(window).load(function() {
		if($.cookie("hide_social_reader")){
			MSI.hide_social_reader($('#social_hiding'), false);
		}
		var social_reader = $('.social_reader');
		var fb_account = $('.social_reader .fb_account');
		var social_reader_login = $('.social_reader_login');
		
		if(social_reader.length == 0){
			return false;
		}

		setTimeout(function(){
			var access_token = '';
			
			try{
				access_token = FB.getAuthResponse()['accessToken'];
			}catch(e){}
			
			FB.api('/me?access_token='+access_token, function(response) {
				if(response.name && user_id){
					MSI.get_friends();
					$('.fb_avatar', fb_account).append('<img src="http://graph.facebook.com/'+ response.id +'/picture?type=square" />');
					$('div.fb_name', fb_account).prepend(response.name);
					social_reader.fadeIn();
					social_reader_login.remove();
					MSI.get_my_feeds();

					//ukrywaczka
					$('#social_hiding').addClass('notscrolled');

					if($.cookie("hide_social_reader")){
						MSI.hide_social_reader($('#social_hiding'));
					} 

					if(user_facebook_shares){
						$('.social_reader .on').fadeIn();
					}else{
						$('.social_reader .off').fadeIn();
					}

					if(demotid && user_facebook_shares){
						setTimeout(function(){MSI.share_add(demotid);}, 10000);
					}
				}else{
					social_reader_login.fadeIn();
					social_reader.remove();
				}
			});
			
			}, 3000);
		
	});
	
	$('.social_reader .user_facebook_shares').live('click', function(event) {
		var self = $(this);
		var disabled = self.hasClass('off');
		
		$.ajax({
			url: "/facebook/share_toggle/"+disabled,
			type: 'GET',
			success: function(data) {
				var data = JSON.parse(data);
				if(data.success == true){
					self.fadeOut('fast');
					if(disabled){
						$('.social_reader .on').fadeIn('slow');
						MSI.turn_on_activities();
					}else{
						$('.social_reader .off').fadeIn('slow');
						MSI.turn_off_activities();
					}
				}
			}
		});
		
			event.preventDefault();
	});
	
	$('.fb_friends .fb_friend.invite').live('click', function(){
		FB.ui({
			method: 'apprequests',
			dispay: 'popup',
			message: 'Zaproszenie na Demotywatory.pl',
			filters: ['app_non_users']
		}, function(response){});
	});
	
	$('#social_hiding').live('click', function(){
		var self = $(this);
		var social_reader = $('.social_reader');
		
		//ukrywamy
		if(self.hasClass('notscrolled')){
			MSI.hide_social_reader(self);
		}else if(self.hasClass('scrolled')){//pokazujemy
			MSI.show_social_reader(self);
		}
	});
	
	$('.fb_friend_container, .fb_avatar').live('click', function(){
		var $this = $(this);
		$this.mouseleave(function(){
			$('.fb_friends_feeds_container, .fb_my_feeds, .fb_coverer').removeClass('visible');
		});
		$this.find('.fb_friends_feeds_container, .fb_my_feeds, .fb_coverer').addClass('visible');
	});



    $(function() {
        var $pageWrapper = $('#page-wrapper');
        var heightfix = false;        
        $(window).scroll(function() {
                    var y = $(this).scrollTop();
                if (y >= 95) {
                    if (!heightfix) {
                        $pageWrapper.addClass('floatheader');
                        heightfix = true;
                    }
                } else {
                    $pageWrapper.removeClass('floatheader');
                    heightfix = false;
                }
            });
            if (logged_in) {
                $(function() {
                    $('body').addClass('logged_in');
                });
            } else if (!logged_in) {
                $('body').removeClass('logged_in');
            }
        });
/*
 * 
 */

